统计单词数 strtok分割函数的用法


title: 统计单词数 strtok分割函数的用法
tag: [acm,c语言]
categories: acm

题目链接

关于strtoc函数的学习:
分割函数,可以将一个字符串按照某个字符分割,
分割原理: 在原来的字符串中指定的那个字符后面加‘’,所以元来的字符串会发生变化;
但是;无法将变化后的字符串全部输出来,因为输出函数遇到''就会认为这个字符串已经结束
请看下面的程序如何将分割后的字符串全部保存下来

//统计一共有多少个不同的单词;

#include<stdio.h>
#include<string.h>
#include<map>
#include<string>
#include<algorithm>
#include<iostream>
#include<set>
using namespace std;
int main()
{
     char a[10005];
     char *temp;
     set<string>s;
     while(gets(a))
     {
         if(a[0]=='#')break;
         temp=strtok(a," ");//将a字符串按照空格来分割 返回的是经过变化的a的首地址
        // printf("%s
",temp);//此时只能输出分割后的第一个字符串
         while(temp!=NULL)
         {
            // puts(temp);
             s.insert(temp);
             temp=strtok(NULL," ");///第二次使用strtoc函数时应将第一个参数设为空,因为第二次使用
                                    ///此函数是,当第一个参数为空时,默认是从上一次截取的位置继续向后截取
         }
         printf("%d
",s.size());
         s.clear();
     }


    return 0;
}
原文地址:https://www.cnblogs.com/dccmmtop/p/6710432.html