【问题标题】:Splitting a string using multiple delimiters in C在 C 中使用多个分隔符拆分字符串
【发布时间】:2016-11-17 17:42:25
【问题描述】:

我目前正在尝试拆分从文本文件中读取分配的字符数组。现在我遇到了分隔符的问题,我不知道我是否可以有多个。我要分隔的是逗号和空格。到目前为止,这是我的代码。

#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?您可以包含文本文件中的示例行吗? “你到目前为止找到的方式”是什么?
  • @thelaws 我添加了更多信息,如果您需要澄清,请告诉我。
  • 您可以在strtok 中使用, 作为分隔符。这里有一个例子:cplusplus.com/reference/cstring/strtok
  • 所以我只需在分隔符数组中添加一个逗号。
  • 无关,你最好希望流读取真的到达EOF并避免任何流错误,否则外循环永远不会终止。请参阅this answer 了解更多信息。

标签: c arrays char variable-assignment delimiter


【解决方案1】:

您可以在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

【讨论】:

  • strtok() 方法的问题是对相邻分隔符序列的潜在错误解释:P1,,,2,3,2 会产生相同的输出,空值无法使用 strtok 解析。
猜你喜欢
  • 2018-04-20
  • 2015-06-29
  • 1970-01-01
  • 2018-02-27
  • 2018-08-18
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多