扩展速记符号字符串 练习3-3

     因为对string类不是很熟悉,不知道如何在string后面直接插入一个字符,所以不得已用指针而为之,缺陷就是一开始必须显示规定扩展字符串的大小。后面有时间了用string来实现以下。不得不得不夸一下K.R这本书,给出的例子或是习题虽然用到的语法规则很简单,但都需要思考一番才能做出来,适合我这种需要提高的菜鸟。

     

#include <stdio.h>
#include <string>
#include<stdlib.h>
using namespace std;

/* exercise 3-3, Write the function expand(s1,s2),expand the string in s1 likes "a-z" into "abcd...xyz" in s2.
the function can deal with capitalization words and ordinary form  ."a-b-c","a-z0-9",can be solved"*/
char* expand(char s[],int max)
{
 char*str=(char*)malloc(sizeof(char)*max);
 int i=0;
 char expander[2];
 int counter=0;
 int strCounter=0;
 
 if(s[0]=='-')
 {
  str[0]='-';
  strCounter++;
  i++;
 }
 for(;s[i]!='\0';i++)
 {
 
  if(s[i]=='-')
  {
   expander[0]=s[i-1];
   expander[1]=s[i+1];
   for(char c=expander[0];c<expander[1];c++)
   {
    str[strCounter]=c;
    strCounter++;
   }
   
  }

  
 }

 str[strCounter]='\0';
 return str;

}

int main()
{
 //test and I always forget add ";" in the end,becareful;

    char *s=expand("-a-d0-9",100);
 while(*s!='\0')
 {
  printf("%c",*s);
  s++;
        
 }
// printf("\n-----%c",s);
 return 0;
}


 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值