strtok and Tokenizing
Split strings.
What is tokenizing?
Tokenizing means splitting a string into smaller pieces (tokens) separated by delimiter characters.
For example, splitting "a,b,c" on commas gives the tokens a, b, and c. C provides strtok for this.
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "a,b,c";
char *token = strtok(text, ",");
printf("First token: %s\n", token);
return 0;
}The strtok signature
char *strtok(char *str, const char *delim);
On the first call you pass the string. On subsequent calls you pass NULL so it continues where it left off. It returns the next token, or NULL when done.
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "red green blue";
char *tok = strtok(text, " ");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, " ");
}
return 0;
}All lessons in this course
- strlen, strcpy, strcat
- strcmp and Comparison
- strtok and Tokenizing
- memcpy and memset