In C, strings are arrays of characters using string manipulation often requires splitting a string into substrings based on multiple delimiters. In this article, we will learn how to split a string by multiple delimiters in C.
Example
Input:
char inputString[] = "Hello,World;This|is.GeeksForGeeks";
char delimiters[] = ",;.|" ;
Output:
Hello
World
This
is
GeeksForGeeks
Split a String into Words by Multiple Delimiters in C
To split a string by multiple delimiters in C, we can use the strtok() function from the standard library. This function allows us to specify multiple delimiters and iteratively extract tokens from the string by calling this function in a loop to get all tokens and when there are no more tokens it returns NULL otherwise, returns the pointer to the first token encountered in the string.
Syntax to Use strtok Function in C
char *strtok(char *str, const char *delims);
Here,
- str is the pointer to the string to be tokenized.
- delims is a string containing all delimiters.
C Program to Split a String by Multiple Delimiters
The following example demonstrates how to split a given string by multiple delimiters in C.
// C program to split a string by multiple delimiters
#include <stdio.h>
#include <string.h>
// Function to split a string by given delimiters
void splitStringByDelimiters(char* inputString,
char* delimiters)
{
// Get the first token
char* token = strtok(inputString, delimiters);
// Loop through the string to extract all other tokens
while (token != NULL) {
// Print each token
printf("%s\n", token);
// Get the next token
token = strtok(NULL, delimiters);
}
}
int main()
{
// Define the input string
char inputString[]
= "Hello,World;This|is.GeeksForGeeks";
// Define the delimiters
char delimiters[] = ",;.|";
// Call the function to split the string by the
// delimiters
splitStringByDelimiters(inputString, delimiters);
return 0;
}
Output
Hello World This is GeeksForGeeks
Time complexity: O(n)
Auxiliary Space: O(1), as strtok() modifies the input string in place and does not require additional space for tokens