I have a string like this:
char *message = "12#34#56#78#90"
I want to get:
a = "12"
b = "34"
c = "56"
d = "78"
d = "90"
Who can give me a good method?
I have a string like this:
char *message = "12#34#56#78#90"
I want to get:
a = "12"
b = "34"
c = "56"
d = "78"
d = "90"
Who can give me a good method?
Use strtok()
. Note that even though that is C++ documentation, the function is also present in C. Take special note to use NULL
in subsequent calls to get the next token.
char label = 'a';
char *token = strtok(message, "#");
while (token != NULL) {
printf("%c = \"%s\"\n", label++, token);
token = strtok(NULL, "#");
}
Outputs:
a = "12"
b = "34"
c = "56"
d = "78"
e = "90"
The strtok function in the standard library does this, you can loop over the string extracting all the tokens.
Let's use strsep - no need to depend on a static variable by passing in NULL.
char *string; // It holds "12#34#56"; (cannot be string literal)
char *token = NULL;
while ((token = strsep(&string, "#"))) {
printf("%s\n", token);
}