分割字符串 c++

可以用strtok

1 char * strtok ( char * str, const char * delimiters ); // 函数原型
 1 /* strtok example */
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 int main ()
 6 {
 7   char str[] ="- This, a sample string.";
 8   char * pch;
 9   printf ("Splitting string \"%s\" into tokens:\n",str);
10   pch = strtok (str," ,.-");
11   while (pch != NULL)
12   {
13     printf ("%s\n",pch);
14     pch = strtok (NULL, " ,.-");
15   }
16   return 0;
17 }

使用strtok需要注意:

1.传参的时候,两个参数必须是char[],即char型数组,不能是char *,否则会报错。至于为什么要如此,是因为首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。strtok在s中查找包含在delim中的字符并用NULL(’\0′)来替换,直到找遍整个字符串。所以字符串不能常量字符串,必须用数组。

这个链接是关于常量字符串的

2.while循环中的strtok(NULL, ...)。至于这里为什么是NULL,而不是原来的字符串,没有找到原因。查了下说是strtok可以记住操作的字符串,每次都会返回分割出来的第一个字符串。

下面这两个链接可以帮助理解:

C语言中利用strtok函数进行字符串分割

break a string into pieces 一个英文论坛

我的程序中是必须使用char *字符串的,所以要把他转成char[],麻烦了一点

必须使用常量字符串时
 1 #include <iostream>
 2 //#include <cstring>
 3 #include <string>  // 包含string头文件
 4 using namespace std;
 5 
 6 int main() {
 7     char *ch = "- this, a sample string.";
 8     string str(ch);  // 构造一个string对象,用ch常量字符串赋值
 9     char *cstr = new char [str.size() + 1];  // new一个char数组,最后记得delete
10     strcpy(cstr, str.c_str());  // 把string对象转成 c string,剩下的操作就正常了
11     char *p = strtok(cstr, " ");
12     while (p != NULL) {
13         cout << p << endl;
14         p = strtok(NULL, " ");
15     }
16     delete []cstr;
17 
18     system("pause");
19     return 0;
20 }

其他的分割字符串方法,度娘上面好多,这个总结的也挺好的      字符串分割(c++)

原文地址:https://www.cnblogs.com/imoon/p/2846754.html