0

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?

why
  • 23,923
  • 29
  • 97
  • 142

4 Answers4

8

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"

See http://ideone.com/xk1uO

moinudin
  • 134,091
  • 45
  • 190
  • 216
  • Thanks! one more question, if I want to get "1234567890", how to do this? – why Dec 28 '10 at 12:16
  • I mean can i get "1234567890" from "12#34#56#78#90" directly? – why Dec 28 '10 at 12:28
  • @why This should really be a separate question. SO is a Q&A site, not a discussion forum. – moinudin Dec 28 '10 at 12:30
  • @why: Maintain two pointers into the string. The destination pointer is initialized to the first '#'. The source pointer to the first digit after the first '#'. When the source pointer finds a valid digit, copy the digit to `*destination++`. Advance source pointer to next digit, repeat until source pointer hits end of string. Assign '\0' to destination pointer. – Thomas Matthews Dec 28 '10 at 18:14
2

The strtok function in the standard library does this, you can loop over the string extracting all the tokens.

fon
  • 141
  • 1
  • 4
1

strtok_r its like strtok but safer. strtok is deprecated.

ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52
1

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);
}
tperk
  • 93
  • 2