strtok的使用
Strtok:原型char *strtok(char s[], const char *delim); s为要分解的字符,delim为分隔符字符(如果传入字符串,则传入的字符串中每个字符均为分割符)。首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。在头文件#include<string.h>中。strtok函数会破坏被分解字符串的完整,调用前和调用后的s已经不一样了。如果要保持原字符串的完整,可以使用strchr和sscanf的组合等。
返回:拆出来字符串首地址
第1个参数:第一次传要拆的串,第二次传NULL(表示向下拆)
第2个参数:用哪些字符做分割符,将分割符改成\0返回
#include <string.h>
void read_all_words1(char (*words)[1000],int *pCnt){
char str[1000000] = {0};
char * p = str;
gets(str);
while(p = strtok(p," ")){
strcpy(words[(*pCnt)],p);
(*pCnt)++;
p = NULL;
}
}
void read_all_words(char (*word)[1000],int *pCnt) {
do{
scanf("%s",word[(*pCnt)]);
(*pCnt)++;
}while(getchar()!='\n');
}
int main(){
char words[1000][1000] = {0};
int cnt = 0;
//read_all_words(words,&cnt);
read_all_words1(words,&cnt);
for(int i = 0;i<cnt;i++){
printf("%s ",words[i]);
}
}