Vipasana Vipasana - 8 months ago 31
C Question

Split string using more than one char as delimeter

Let's say I have a string

"file1.h: file2.c,file3.cpp"
and I want to split it into
- that is using
and whitespace) as delimiter. How can I do it?

I tried this code with no help:

int main(int argc, char *argv[]) {
char str[] = "file1.h: file2.c,file3.cpp";
char name[100];
char depends[100];
sscanf(str, "%s: %s", name, depends);
printf("Name: %s\n", name);
printf("Deps: %s\n", depends);

And the output I get is:

Name: file1.h:



What you seem to need is strtok(). Read about it in the man page. Related quote from C11, chapter ยง7.24.5.8

A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. [...]

In your case, you can use a delimiter like

  char * delim = ": "; //combination of : and a space

go get the job done.

Things to mention additionally,

  • the input needs to be modifiable (which is, in your case) for strtok()
  • and it actually destroys the input fed to it, keep a copy around if you need the actual later.