0 day streak
c / intermediate
Snippet

Parsing Strings with strtok

The 'strtok' function is used to split a string into a series of tokens based on a delimiter. Note that 'strtok' modifies the original string by replacing delimiters with null terminators and maintains internal state for subsequent calls.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <string.h>
int main() {
char data[] = "C,Java,Python";
char *token = strtok(data, ",");
while (token != NULL) {
printf("Language: %s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
Breakdown
1
strtok(data, ",")
Initializes parsing of 'data' using a comma as a delimiter.
2
strtok(NULL, ",")
Continues parsing the same string from where the previous call left off.