How to Split a String by a Delimiter in C?
Splitting a string by a delimiter is a common task in programming. In C, strings are arrays of characters, and there are several ways to split them based on a delimiter. In this article, we will explore different methods to split a string by a delimiter in C.
Splitting Strings in C
The strtok() method splits str[] according to given delimiters and returns the next token. It needs to be called in a loop to get all tokens. It returns NULL when there are no more tokens.
Syntax of strtok()
char *strtok(char *str, const char *delims);
Parameters
- str: It is the pointer to the string to be tokenized.
- delims: It is a string containing all delimiters.
Return Value
- It returns the pointer to the first token encountered in the string.
- It returns NULL if there are no more tokens found.
C program for splitting a string
C Program to demonstrate how to split a string using strtok().
// C program for splitting a string
// using strtok()
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Beginner-for-Beginner-is-a-computer-science-portal";
// Returns first token
char* token = strtok(str, " - ");
// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL) {
printf(" % s\n", token);
token = strtok(NULL, " - ");
}
return 0;
}
Output
Beginner for Beginner is a computer science portal
Time complexity : O(n)
Auxiliary Space: O(n), where n is the number of characters in the string.