因为对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;
}