在C中使用多个定界符分割字符串 [英] Splitting a string using multiple delimiters in C
问题描述
我目前正在尝试拆分从文本文件读取分配的字符数组.现在,我在定界符方面遇到了麻烦,我不知道是否可以有多个定界符.我要划定的是逗号和空格.到目前为止,这是我的代码.
#include< stdio.h>FILE * fPointer;fPointer = fopen(文件名","r");char singleLine [1500];字符定界符[] =int i = 0;int j = 0;int k = 0;while(!feof(fPointer)){//i计数器用于我要跳过的文本文件中的第一行while((fgets(singleLine,1500,fPointer)!= NULL)& !!(i == 0)){//在此循环中定界puts(singleLine);}i ++;}fclose(fPointer);返回0;}
到目前为止,我发现的是一种使用带有制表符等缩写形式的文本字符串来定界的方法.
char Delimit [] ="/n/t/f/s";
然后我将在strtok()方法中的定界符参数下使用此字符串
但这不会让我用逗号作为定界符.
这就是要点,因此我可以开始将定界的字符串分配给变量.
样本输入:P1,2,3,2
感谢任何帮助或参考.
您可以在 strtok
方法中使用,
作为分隔符.
我还认为您打算将 \ n \ t
用于换行符和制表符(我不知道/f/s
是什么意思)./p>
尝试使用此:
char Delimit [] =,\ n \ t";//< snip>字符*令牌= strtok(单行,分隔符);while(令牌!= NULL){//在这里使用令牌printf(%s \ n",令牌);//从singleLine获取下一个令牌令牌= strtok(NULL,分隔符);}
这会将您的示例输入 P1,2,3,2
转换为:
P12个32个
I'm currently trying to split an array of chars that is assigned from reading in from a text file. right now I'm having troubles with delimiters and I don't know if I can have multiple. what I want to delimit is commas and spaces. Here is my code so far.
#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;
}
What I've found so far is a way to delimit using a string of text that has shorthand for tabs and such e.g.
char Delimit[] = " /n/t/f/s";
then I would use this string in the strtok() method under the delimiter parameter
but this wont let me have a comma as a delimiter.
And the whole point of this is so I can start to assign the delimited strings into variables.
sample input: P1,2, 3 , 2
Any help or references is appreciated thanks.
You can use a ,
as a delimiter in the strtok
method.
I also think you meant to use \n\t
for newlines and tabs (I don't know what /f/s
is meant to represent).
Try using this:
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);
}
That would transform your sample input P1,2, 3 , 2
into:
P1
2
3
2
这篇关于在C中使用多个定界符分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!