Split a String by Space in C

In C, we can split a string by spaces using various methods, such as strtok(), manual iteration with loops, and sscanf(). These methods help us break a sentence into individual words efficiently.

In this tutorial, we will explore multiple approaches to split a given string by space character, with detailed explanations and examples.


Examples to Split a String by Space

1. Splitting a String Using strtok()

In this example, we will use the strtok() function from string.h to split a string into words using space as the delimiter.

main.c

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

int main() {
    char str[] = "Hello World from C";
    char *token = strtok(str, " ");

    // Loop through tokens
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, " ");
    }

    return 0;
}

Explanation:

  1. We declare a character array str with the sentence "Hello World from C".
  2. We use strtok() to extract the first token (word) separated by a space.
  3. A while loop is used to repeatedly call strtok(NULL, " ") until no tokens remain.
  4. Each token (word) is printed on a new line.

Output:

Hello
World
from
C

2. Splitting a String Using Loops and isspace()

In this example, we will manually iterate through the string using a while loop, detecting spaces using isspace() from ctype.h, and extract words.

main.c

</>
Copy
#include <stdio.h>
#include <ctype.h>

void splitString(const char *str) {
    int i = 0;
    while (str[i] != '\0') {
        if (!isspace(str[i])) {
            while (str[i] != '\0' && !isspace(str[i])) {
                putchar(str[i]);
                i++;
            }
            putchar('\n');
        } else {
            i++;
        }
    }
}

int main() {
    char str[] = "apple banana cherry mango";
    splitString(str);
    return 0;
}

Explanation:

  1. The function splitString() takes a string and iterates through it character by character.
  2. isspace() is used to check if a character is a space.
  3. When a non-space character is found, a nested loop prints the word until another space or '\0' is encountered.
  4. Each word is printed on a new line.

Output:

apple
banana
cherry
mango

3. Splitting a String Using sscanf()

In this example, we will use sscanf() to extract words from a string.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "apple banana cherry";
    char word1[10], word2[10], word3[10];

    sscanf(str, "%s %s %s", word1, word2, word3);

    printf("%s\n%s\n%s\n", word1, word2, word3);
    
    return 0;
}

Explanation:

  1. We declare a character array str containing the sentence.
  2. Three character arrays word1, word2, and word3 are used to store the extracted words.
  3. The sscanf() function extracts words separated by spaces and stores them in the respective variables.
  4. The extracted words are printed on separate lines.

Output:

apple
banana
cherry

Conclusion

In this tutorial, we explored different ways to split a string by space in C:

  1. strtok(): Easy and efficient but modifies the original string.
  2. Manual iteration with isspace(): Suitable for custom implementations without modifying the input.
  3. sscanf(): Useful when you know the number of expected words.