c語言字元串拆分
㈠ c語言怎麼把字元串按行分割
int split(char dst[][80], char* str, const char* spl)
{
int n = 0;
char *result = NULL;
result = strtok(str, spl);
while( result != NULL )
{
strcpy(dst[n++], result);
result = strtok(NULL, spl);
}
return n;
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[] = "123,456 789,321";
char dst[10][80];
int cnt = split(dst, str, " ");
for (int i = 0; i < cnt; i++)
puts(dst[i]);
return 0;
}

主要是字元串分割函數strtok的使用
㈡ 關於c語言字元串中切割函數strtok的用法
strtok()函數並不像你想的那樣可以一次切割字串。需要多次循環,第二次時需要用 p = strtok(NULL, " "); 這樣的 形式。
void main()
{ char test1[] = "Hello C World";
char *p;
p = strtok(test1, " ");
while(p)
{
printf("%s\n", p);
p = strtok(NULL, " ");
}
return 0;
}
運行結果:
Hello
C
World
㈢ C語言有沒有把字元串拆分為數組的函數
直接用簡單的C++
#include<iostream>
#include<string>
#include<vector>
usingnamespacestd;
//把字元串s按照字元串c進行切分得到vector_v
vector<string>split(conststring&s,conststring&c){
vector<string>v;
intpos1=0,pos2;
while((pos2=s.find(c,pos1))!=-1){
v.push_back(s.substr(pos1,pos2-pos1));
pos1=pos2+c.size();
}
if(pos1!=s.length())
v.push_back(s.substr(pos1));
returnv;
}
intmain()
{
stringinput="張三$|男$|濟南$|大專學歷$|";
vector<string>myArray=split(input,"$|");
for(inti=0;i<myArray.size();i++){
cout<<myArray[i]<<endl;
}
}
/*
張三
男
濟南
大專學歷
*/
㈣ C語言輸入一個字元串,然後分割成三個,規則入內
int main()
{
char buf[];//buf為你的帶空格的字元串
char arr1[]; //以下為分別用以存儲的字元數組
char arr2[];
.
.
.
int i = 0;
int counts = 1; //循環計數
char*p =& buf[0]; //讀指針
while(*p!='\0')
{
if(' '==*p)
{
p++;
continue;
}
else
{
switch(counts)
{
case:1
while((arr1[i++] = *p++)&&(*p!=' '));
break;
case:2
while((arr2[i++] = *p++)&&(*p!=' '));
break;
.
.
.
}
}
counts++;
i= 0;
}
return 0;
}
大體思路,沒有編譯,上班倉促寫了個框架,哈哈
