面向对象程序设计(基于C++)0103 单词出现次数

题目

在这里插入图片描述

思路

首先可以进行长度判断,长度都不一样就不用谈是同一个单词了
然后长度相同就逐个比较即可,需要注意开头和结尾的特殊判断

代码

#include<iostream>
#include<string>
using namespace std;

long long cnt(string & all, string & word)
{
    if(word.length() > all.length())
    {return 0;}

    long long count = 0;
    string one = all.substr(0,word.length());
    
    int position_2 = all.find(" ");
    
    

    
    if(one == word && (position_2 == word.length() || word.length() == all.length() ))
    {count++;}

    int position_1 = position_2;
    
    while((position_2) != all.npos)
    {
        position_2 = all.find(" ",position_1 + 1);
        int each_len;
        if(position_2 != all.npos)
        {
            each_len = position_2 - position_1 - 1;
        }
        else
        {
            each_len = all.length() - position_1 - 1;
        }
        
        

        string temp = all.substr(position_1 + 1, word.length());
        position_1 = position_2;

        if(temp == word && each_len == word.length())
        {count ++;}
        //cout << count << "??? "<< endl;
    }

    return count;

}

int main()
{
    int total;
    cin >> total;
    getchar();
    for(int i = 0; i < total; i++)
    {
        string all;
        getline(cin, all);
        //cout << all << endl;
        string word;
        cin >> word;
        getchar();//
        //cout << word<<endl;
        cout << "case #" << i << ":"<<endl;
        cout << cnt (all, word) << endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值