How to Split a String in C


ANSI C is one of the oldest and most widely used lower level programming languages still in use by modern, professional programmers. What it lacks in convenient features it makes up for in raw power and speed. One common task is to break up series of characters called strings into smaller strings. For example, you may want to get each piece of data from a comma separated string of data.

  • Open your favorite C language Integrated Development Environment (IDE), and start a new console project. The details of starting a new project vary depending on the IDE you choose, but generally you’ll click \"File > New > Project\" and select \"Console Application\" when presented with options for the application type.

  • Copy and paste the following code into main.c:

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

    int main (char str[], char spl)
    char *p

    printf (\"Split \\"%s\\" in tokens:\n\", str)

    p = strtok (str, spl)

    while (p != NULL)

    printf (\&quot;%s\\n\&quot;, p)


    p = strtok (NULL, \&quot; ,\&quot;)

    return 0

  • Compile the console application using your IDE to an executable named \"split.exe.\"

  • Run split.exe on the command line by typing the following command:

    split \"This is the string to split\" \" \"

    (All quotation marks are elements of the command. The last two of the four shown are open-quotation marks.)

Related Searches


Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!