hdu 2072 Message

题意:
统计不同单词的数量。
解法:
使用string和map,输入字符串后找到第一个非空格的字符的位置记录为b,再找到后面第一个为空格的字符记为e,单词即为str.substring(b,e-b);,重复上述过程直到结束,最后还要判断一下是否落了最后一个单词。
总结:
第一次写的时候用了char数组,写得很繁琐。现在改用string,代码简短,思路清晰。还可以使用strtok函数对char数组进行分割。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<string>
#include<cstring>
#include<vector>
#include<stack>
#include<map>
#include<algorithm>
using namespace std;
#define PI 3.1415927
const double MAXNUM=0xffff;
const int INF = 100000000;

int main()
{
     int n,m;
     string str;

     while(getline(cin,str)){
            if(str[0]=='#') break;
           map<string,int> wordRecord;
           int b,e;
           b=-1;
           for(int i=0;i<str.length();i++){
                if(str[i]!=' '&&b==-1){
                    b=i;
                }
                else if(i>0&&str[i]==' '&&b!=-1){
                    e = i;
                    string w = str.substr(b,e-b);
                if(wordRecord.count(w)==0){
                    wordRecord[w]=1;
                }
                b=-1;
                }

           }

           if(b!=-1){
               string w = str.substr(b,str.length()-b);
                if(wordRecord.count(w)==0){
                    wordRecord[w]=1;
                }
         
           }
            cout<<wordRecord.size()<<endl;
   }
     return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值