C语言以sscanf逗号作为分割符
char buf_a[10]={0}; char buf_c[10]={0}; char buf_b[5]={0}; sscanf("/dev/ttyS0,115200,8,1,n","%[^,],%[^,],%[^,],%[^,],%s",buf_a,buf_c,&buf_b[1],&buf_b[2],&buf_b[3]); printf("*****************\n"); printf("%s\n", buf_a); printf("%s\n", buf_c); printf("%c\n", buf_b[1]); printf("%c\n", buf_b[2]); printf("%c\n", buf_b[3]);
以strtok作为分割符
char str[]="/dev/ttyS0,115200,8,1,n"; char *result=NULL; result=strtok(str,","); while(result!=NULL){ printf("result is \"%s\"\n",result); result = strtok(NULL,","); }
C++ 逗号分割符
vector<string> split(string str, string pattern){
string::size_type pos;
vector<string> result;
str+=pattern;
int size = str.size();
for(int i=0; i<size; i++){
pos = str.find(pattern,i);
if(pos<size){
string s = str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}
std::string pattern=",";
std::string str="/dev/ttyS0,115200,8,1,n";
std::vector<std::string>result = split(str,pattern);
for(int i=0;i<result.size();i++){
cout<<"aaa:"<<result[i]<<endl;
}
时间: 2024-11-25 16:01:14