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]);
    }
}
#include<stdio.h>
#include<string.h>
enum status{
   BLANK,CHAR};
int fun(char str[]){
   
    int words = 0;
    char temp[100] = {
   " "};
    strcat(temp,str);
    strcat(temp," ");
    for(int i = 1;i<= strlen(temp)-2;i++){
   
        if(temp[i] != ' ' && temp[i-1] == ' '){
   
            words ++;
        }
    }
    return words;
}
int main(){
   
    char * p = "i am a boy";
    printf("%d",fun(p));
}
#include<stdio.h>
#include<string.h>
enum status{
   BLANK,CHAR};
int fun(char str[]){
   
    int words = 0;
    char temp[100] = {
   " "};
    strcat(temp,str);
    strcat(temp," ");
    for(int i = 1;i<= strlen(temp)-1;i++){
   
        if(temp[i] != ' ' && temp[i-1] == ' '){
   
            words ++;
        }
    }
    return words;
}
int main(){
   
    char * p = "i am a b";
    printf("%d",fun(p));
}

相关推荐

  1. strtok使用

    2024-02-06 23:12:08       28 阅读
  2. 使用C语言strtok函数来分割字符串

    2024-02-06 23:12:08       39 阅读
  3. c语言字符串分割函数strtok_s和strtok

    2024-02-06 23:12:08       30 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-06 23:12:08       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-06 23:12:08       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-06 23:12:08       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-06 23:12:08       20 阅读

热门阅读

  1. QT - 嵌入式快速移植QT记录

    2024-02-06 23:12:08       30 阅读
  2. K8S-Service

    2024-02-06 23:12:08       31 阅读
  3. 【计算机二级考试C语言】C可变参数

    2024-02-06 23:12:08       27 阅读
  4. gerrit(2) | 为什么使用 gerrit

    2024-02-06 23:12:08       35 阅读
  5. C++泛型编程:模板偏特化

    2024-02-06 23:12:08       34 阅读