使用strtok、sscanf和strpbrk分别解析字符串的方法

2011-03-13 wcdj

 

类似问题:如:char sdate[]="#1,3,5,16(1)"; 怎样才能把1,3,5,16,1分别单独取出来,“1,3,5,16,1”长度不固定。

 

方法1:使用strtok

#include<iostream> #include <cstring> using namespace std; int main() { char sdate[]="#1,3,5,16(1)"; char * pch = strtok(sdate, "#,()"); while (pch) { printf("%s ",pch); pch = strtok(NULL, "#,()"); } system("pause"); return 0; }

输出:
1 3 5 16 1

 

方法2:使用sscanf和strpbrk

#include<iostream> #include <cstring> using namespace std; int main() { char str[] = "#1,3,5,16(1)"; char key[] = "#,()"; int d = 0, r = 0; char * pch; pch = strpbrk (str, key); while (pch != NULL) { //printf ("%c " , *pch); while (*pch) { r = sscanf(pch, "%d", &d); if (r == 1) { printf("%d ", d); break; } else if (r == 0) sscanf(pch++, "%*c"); } if (pch == NULL) break; pch = strpbrk (pch+1,key); } system("pause"); return 0; }

输出:
1 3 5 16 1

 

以前总结的另一篇文章:scanf中%[*]type的巧用场景


参考:
strtok
strpbrk

 

 

你可能感兴趣的:(c,null,System)