Usage of strtok function in C language

** The strtok function is a function in the string.h library.
Prototype: char * strtok (char s, const char delim);
strtok () is used to split the string into fragments. The parameter s points to the character string to be divided, and the parameter delim refers to all characters contained in the divided character string. When strtok () finds the split character contained in the parameter delim in the string of the parameter s, it will change the character to the \ 0 character. Only in the first call, strtok () must be given the parameter s string, and subsequent calls will set the parameter s to NULL. Each successful call returns a pointer to the segment. When there is no split string, it returns NULL. All characters contained in the delim will be filtered out, and the filtered out place will be set as a split node.

Example: Word statistics
Problem description:
Enter a line of characters and use function programming to count how many words there are.
Note: Any string separated by spaces is considered a word. For example, "I'm" is regarded as a word
. The function prototype of counting the number of words is: int CountWords (char str []);

#include<stdio.h>
#include<string.h>
int CountWords(char str[]){
	int sum=0;
	char *token;
     token=strtok(str," ");
	 while(token!=NULL){
         sum++;
        token=strtok(NULL," ");
	 }
	return sum;
}
int main(){
	char str[20];
	gets(str);
    printf("%d",CountWords(str));
	return 0;
}
Published 12 original articles · Like1 · Visits 197

Guess you like

Origin blog.csdn.net/qq_39338091/article/details/104746683