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
#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:
- We declare a character array
str
with the sentence"Hello World from C"
. - We use
strtok()
to extract the first token (word) separated by a space. - A
while
loop is used to repeatedly callstrtok(NULL, " ")
until no tokens remain. - 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
#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:
- The function
splitString()
takes a string and iterates through it character by character. isspace()
is used to check if a character is a space.- When a non-space character is found, a nested loop prints the word until another space or
'\0'
is encountered. - 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
#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:
- We declare a character array
str
containing the sentence. - Three character arrays
word1
,word2
, andword3
are used to store the extracted words. - The
sscanf()
function extracts words separated by spaces and stores them in the respective variables. - 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:
strtok()
: Easy and efficient but modifies the original string.- Manual iteration with
isspace()
: Suitable for custom implementations without modifying the input. sscanf()
: Useful when you know the number of expected words.