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?

1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! one more question, if I want to get "1234567890", how to do this?
I mean can i get "1234567890" from "12#34#56#78#90" directly?
@why This should really be a separate question. SO is a Q&A site, not a discussion forum.
@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.
2

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

Comments

1

strtok_r its like strtok but safer. strtok is deprecated.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.