split a string by empty space in C
Code snippet on how to split a string by empty space in C
#include<stdio.h>
#include<string.h>
int main()
{
char str[] = "This is a String";
char *ptr;
ptr = strtok(str, " ");
while (ptr != NULL)
{
printf("%s\n", ptr);
ptr = strtok(NULL, " ");
}
return 0;
}
This code uses the strtok()
function from the string.h
library to split a string by an empty space in C. First, the string str
is initialized to “This is a String” and the pointer ptr
is pointing to the beginning of the string. The strtok()
function takes two arguments - the string and the delimiter which is the empty space in this case. The strtok()
function splits the string from the first argument and returns a token. The strtok()
function searches for the characters in the second argument for splitting the string. The NULL
argument in the second parameter tells strtok()
to continue splitting the string one token at a time. The output of the code is the printing of the tokens on separate lines.