Splitting a string using multiple delimiters in C

家住魔仙堡 提交于 2021-01-29 07:30:56

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/38380419/splitting-a-string-using-multiple-delimiters-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!