strtok的使用

本文介绍了C语言中的strtok函数用法,包括其原型、参数以及如何结合gets和scanf在两个不同函数read_all_words1和read_all_words中实现字符串的分解。还展示了如何使用fun函数统计连续非空字符组成的单词数量。
摘要由CSDN通过智能技术生成

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值