字符串处理三题之二

来源:互联网 发布:mac word简繁体切换 编辑:程序博客网 时间:2024/06/05 09:36

【问题1】

输入一个字符串,把字符串中的字母后移一个,a->b, b->c.......z->a,  A->B,B->C,.......Z->A;其他内容不改变。然后输出。

函数声明: void Func(char * pIn, char * pOut);

【实现代码】

void Func(char *pIn, char *pOut){for(; *pIn != '\0'; pIn++){if(*pIn !='z' && *pIn != 'Z' && isalpha(*pIn)){*pOut++ =  *pIn + 1;}else if(*pIn == 'z'){*pOut++ = 'a';}else if(*pIn == 'Z'){*pOut++ = 'A';}else{*pOut++ = *pIn;}}*pOut = '\0';}


【测试代码】

char *in = "Hello World!";char *out = NULL;out = (char *)malloc((strlen(in)+1)*sizeof(char));//memset(out,0,(strlen(in)+1)*sizeof(char));Func(in, out);printf("%s\n",in);printf("%s\n",out);free(out);

 

【问题2】

输入一个数,把它作为一个串,判断其中是否包含长度>=2的相同子串,如果包含,返回1,不包含,返回0;

例如:输入 12312,包含两个“12”子串,返回1.

           输入 1223122,包含两个“122”子串,返回1.

 

【实现代码】

bool Test::findString(string in){bool find = false;const char *buf = in.c_str();int length = in.length();if(length < 3){find = false;}else if(length == 3){find = (buf[0] == buf[1] && buf[1] == buf[2]) ? 1 : 0;}else{for(int i = 0; i < length-1; i++){for(int j = i+1; j + 1 < length; j++){if(buf[j]==buf[i]){if(buf[j+1]==buf[i+1]){find = true;return find;}}}}}return find;}


【测试代码】

bool find = false;string str;cin>>str;Test test;find = test.findString(str);cout<<find<<endl;


【问题3】

输入一个字符串,将所有的小写字母转换为大写字母。并将其逆序排列。

 

【实现代码】

int invert(char *pIn, char *pOut){char *start = pOut;char *end = pOut + strlen(pIn);int i = 0;for(; *pIn != '\0'; ){*pOut++ = toupper(*pIn++);i++;}pOut = pOut - i;for(; end-- > start; ){char temp = *start;*start = *end;*end = temp;start++;}return 0;}


【测试代码】

char in[20];char out[20];//memset(out, 0, 20);scanf("%s", &in);printf("%s\n", in);invert(in, out);printf("%s\n", out);

 

 

 

转载请标明出处,仅供学习交流,勿用于商业目的

Copyright @ http://blog.csdn.net/tandesir

 


 

 

 


 

 

原创粉丝点击