猿问

你好,在C语言中有没有把字符串拆分为数组的函数?如果有,请问是?

张三$|男$|济南$|大专学历$|
如上是一个字符串, 把上面的字符串按 $| 分成一个数组。如:
myArray[0] = "张三";
myArray[1] = "男";
myArray[2] = "济南";
myArray[3] = "大专学历";
C语言有没有提供相关函数啊? 如果没有能帮我写一个吗,谢谢。
要求能支持中文的。

浮云间
浏览 158回答 3
3回答

翻阅古今

直接用简单的C++#include&nbsp;<iostream>#include&nbsp;<string>#include&nbsp;<vector>using&nbsp;namespace&nbsp;std;&nbsp;//把字符串s按照字符串c进行切分得到vector_v&nbsp;vector<string>&nbsp;split(const&nbsp;string&&nbsp;s,&nbsp;const&nbsp;string&&nbsp;c){&nbsp;&nbsp;&nbsp;&nbsp;vector<string>&nbsp;v;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;pos1=0,pos2;&nbsp;&nbsp;&nbsp;&nbsp;while((pos2=s.find(c,pos1))!=-1){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;v.push_back(s.substr(pos1,&nbsp;pos2-pos1));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pos1&nbsp;=&nbsp;pos2&nbsp;+&nbsp;c.size();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;if(pos1&nbsp;!=&nbsp;s.length())&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;v.push_back(s.substr(pos1));&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;v;&nbsp;}&nbsp;&nbsp;int&nbsp;main(){&nbsp;&nbsp;&nbsp;&nbsp;string&nbsp;input="张三$|男$|济南$|大专学历$|";&nbsp;&nbsp;&nbsp;&nbsp;vector<string>&nbsp;&nbsp;myArray=split(input,"$|");&nbsp;&nbsp;&nbsp;&nbsp;for(int&nbsp;i=0;i<myArray.size();i++){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout<<myArray[i]<<endl;&nbsp;&nbsp;&nbsp;&nbsp;}}/*张三男济南大专学历*/

交互式爱情

用strtok函数实现吧。void split( char **arr, char *str, const char *del)//字符分割函数的简单定义和实现{char *s =NULL;s=strtok(str,del);while(s != NULL){*arr++ = s;s = strtok(NULL,del);}}int main(){int i;char *myArray[4];char s[] = "张三$|男$|济南$|大专学历$|";memset(myArray, 0x0, sizeof(myArray));split(myArray, s, "$|");for (i=0; i<4; i++){printf("%s\n", myArray[i]);}return 0;}

慕莱坞森

char str[] = "now $| is the time for all $| good men to come to the $| aid of their country";char delims[] = "$|";char *result = NULL;result = strtok( str, delims );while( result != NULL ){printf( "result is \"%s\"\n", result );result = strtok( NULL, delims );}以上代码的运行结果是:result is "now "result is " is the time for all "result is " good men to come to the "result is " aid of their country"&nbsp;
随时随地看视频慕课网APP
我要回答