[英]C++: Splitting a string with multiple delimiters and keep the delimiters in the results?
[英]Splitting a string using multiple delimiters in C
我目前正在尝试拆分从文本文件读取分配的字符数组。 现在我在定界符方面遇到了麻烦,我不知道是否可以有多个。 我要划定的是逗号和空格。 到目前为止,这是我的代码。
#include <stdio.h>
FILE * fPointer;
fPointer = fopen("file name", "r");
char singleLine[1500];
char delimit[] =
int i = 0;
int j = 0;
int k = 0;
while(!feof(fPointer)){
//the i counter is for the first line in the text file which I want to skip
while ((fgets(singleLine, 1500, fPointer) != NULL) && !(i == 0)){
//delimit in this loop
puts(singleLine);
}
i++;
}
fclose(fPointer);
return 0;
}
到目前为止,我发现的是一种使用带有制表符缩写的文本字符串来定界的方法,例如
char Delimit[] = " /n/t/f/s";
那么我将在strtok()方法中的delimiter参数下使用此字符串
但这不会让我用逗号作为分隔符。
这样做的重点是让我可以开始将分隔的字符串分配给变量。
样本输入:P1,2,3,2
任何帮助或参考表示赞赏,谢谢。
您可以使用,
作为分隔符strtok
方法。
我还认为您打算对换行符和制表符使用\\n\\t
(我不知道/f/s
代表什么)。
尝试使用此:
char Delimit[] = " ,\n\t";
// <snip>
char * token = strtok (singleLine, Delimit);
while (token != NULL)
{
// use the token here
printf ("%s\n",token);
// get the next token from singleLine
token = strtok (NULL, Delimit);
}
这会将您的样本输入P1,2, 3 , 2
转换为:
P1
2
3
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.