acm 洛谷 P1308 统计单词数 题解 【字符串】

题目类型:字符串
题目来源:https://www.luogu.org/problemnew/solution/P1308

思路:
【1】查找单词出现的第一次位置可以使用string::find()函数,主要要在目标单词旁边各加一个空格
【2】统计单词个数,可以使用记录状态来,看代码

代码


#include <iostream>
#include <string>
#include <string.h>
#include <vector>
#include <stdio.h>
#include <algorithm>
using namespace std;

int total;
char word[15];
char artice[1000005];
void tolow();
void coun();
int main(){
    gets(word);
    gets(artice);
    tolow();
    coun();
    string str(artice);
    string str2(word);
    str = ' '+str;
    size_t startIndex = str.find(' '+str2+' ');
    if(startIndex == string::npos)
        cout<<"-1";
    else
        cout<<total<<" "<< startIndex;
    return 0;
}

void tolow(){ //将所有的大写字母改成小写
    for(int i = 0;artice[i]!='\0';i++){
        artice[i] = (char)tolower(artice[i]);

    }
    for(int i = 0;word[i]!='\0';i++){
        word[i] = (char)tolower(word[i]);
    }
}

void coun(){//统计目标单词个数
    bool sign = false;//false--不能开始匹配 true---可以开始匹配
    for(int i = 0;artice[i]!='\0';){
        if(sign){//开始匹配
            int j;
            for(j = 0;word[j]!='\0'&&artice[i]!='\0'&&artice[i]!=' ';j++,i++){ //一一匹配
                if(word[j]!=artice[i]){
                    break;
                }
            }
            if(word[j] == '\0' && (artice[i] == ' '||artice[i]=='\0')){
                total++;//单词数+1
            }
            for(;artice[i]!=' '&&artice[i]!='\0';i++){//匹配失败后,跳过无效的字母
                ;
            }
            sign = false;
        }else{//跳过空格
            for(;artice[i]==' ';i++){
                ;
            }
            sign = true;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值