1

Is there any pre-defined function in C that can split a string given a delimeter? Say I have a string:

"Command:Context"

Now, I want to store "Command" and "Context" to a two dimensional array of characters

char ch[2][10]; 

or to two different variables

char ch1[10], ch2[10];

I tried using a loop and it works fine. I'm just curious if there is such function that already exists, I don't want to reinvent the wheel. Please provide a clear example, thank you very much!

2 Answers 2

6

You can use strtok

Online Demo:

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] ="Command:Context";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str,":");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, ":");
    }
    return 0;
}

Output:

Splitting string "Command:Context" into tokens:
Command
Context
Sign up to request clarification or add additional context in comments.

2 Comments

No example in the article. Please guide me :(
+1 For online demo... Sir, if the string is "Command Context", it's still giving me "Command" and "Context" instead of "Command Context"...
2

You can tokenise a string with strtok as per the following sample:

#include <stdio.h>
#include <string.h>

int main (void) {
    char instr[] = "Command:Context";
    char words[2][10];
    char *chptr;
    int idx = 0;

    chptr = strtok (instr, ":");
    while (chptr != NULL) {
        strcpy (words[idx++], chptr);
        chptr = strtok (NULL, ":");
    }

    printf ("Word1 = [%s]\n", words[0]);
    printf ("Word2 = [%s]\n", words[1]);

    return 0;
}

Output:

Word1 = [Command]
Word2 = [Context]

The strtok function has some minor gotchas that you probably want to watch out for. Primarily, it modifies the string itself to weave its magic so won't work on string literals (for example).

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.