kazinix
kazinix

Reputation: 30153

C - Split a string

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!

Upvotes: 1

Views: 648

Answers (2)

paxdiablo
paxdiablo

Reputation: 882586

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).

Upvotes: 2

Alok Save
Alok Save

Reputation: 206636

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

Upvotes: 6

Related Questions