How to use sscanf to tokenize a string in C language?
One example of using the sscanf function to split a string according to a specified format.
#include <stdio.h>
int main() {
char str[] = "Hello,World,C Language";
char word1[10], word2[10], word3[10];
sscanf(str, "%[^,],%[^,],%s", word1, word2, word3);
printf("Word 1: %s\n", word1);
printf("Word 2: %s\n", word2);
printf("Word 3: %s\n", word3);
return 0;
}
In the above example, we defined a string str containing three words separated by commas. We used the sscanf function to store these words in arrays word1, word2, and word3 respectively.
In the format string of the sscanf function, %[^,] matches any character except for a comma, while %s matches a sequence of non-empty characters. By using a comma to separate these format specifiers in the format string, the effect of splitting a string by commas can be achieved.
Running the above code will produce the following output:
Word 1: Hello
Word 2: World
Word 3: C Language
The string has been successfully split and stored in the corresponding array.