Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to split a string on multiple characters in C?

Tags:

c

string

split

Is there a way in C to split a string (using strtok or any other way) where the delimiter is more than one character in length? I'm looking for something like this:

char a[14] = "Hello,World!";
char *b[2];
b[0] = strtok(a, ", ");
b[1] = strtok(NULL, ", ");

I want this to not split the string because there is no space between the comma and the W. Is there a way to do that?

like image 945
Daniel Avatar asked Aug 16 '11 14:08

Daniel


2 Answers

You could just repeatedly call substr to find occurrences of your boundary string and split along the results. After you found a result, advance the pointer by the length of the substring and search again.

like image 122
Kerrek SB Avatar answered Oct 29 '22 21:10

Kerrek SB


You can use char * strstr(const char *haystack, const char *needle) to locate your delimiter string within your string.

char a[14] = "Hello,World!";
char b[2] = ", ";
char *start = a;
char *delim;
do {
    delim = strstr(start, b);
    // string between start and delim (or end of string if delim is NULL).
    start = delim + 2; // Use lengthof your b string.
} while (delim);
like image 45
Didier Trosset Avatar answered Oct 29 '22 19:10

Didier Trosset