#include <stdio.h> #include<stdlib.h> #include<windows.h> void DivideString(const char *str,long len,char *outstr) { for(int i=0;i<len;i++) { if(str[i]!=' ') { *outstr++ = str[i]; } else if ((str[i]==' ')&&str[i+1]!=' ') { *outstr++ = ','; } } *outstr++ = ','; *outstr++='\0'; } void main() { char *str = "abc def shkfdafd f"; int len = strlen(str); char * outstr = (char*)malloc(len*sizeof(char)); DivideString(str,len,outstr); printf("%s",outstr); free(outstr); outstr = NULL; system("pause"); }
解析:本题目比较简单,就是识别出空格,然后把多余的空格过滤掉,换上逗号,当然记得在字符串的结尾加上一个逗号以及‘\0’。