统计单词数

本文介绍了一个使用C++实现的简单字符串搜索程序,该程序能够忽略大小写,并找到文章中首次出现关键字的位置及其出现次数。涉及字符串处理、大小写转换等基本操作。
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
/* 耗时什么的,完全不在乎了,已经被搞吐了 */
void stolower(string& str)
{
    for(int i = 0; i < str.size(); i++)
        if(isalpha(str[i]))
            str[i] = tolower(str[i]);
}
int pos[1000000 + 10];
int main()
{
    string key, word;
    string article;
    char c_key[30];
    while(cin.peek() == ' ')
        cin.ignore();
    cin.getline(c_key, 30);
    if (cin.peek() == '\n')
        cin.ignore();
    for(int i = 0; i < 15; i++)
    {
        if(!isalpha(c_key[i]))
        {
            c_key[i] = 0;
            break;
        }
    }
    key = c_key;
    stolower(key);
    
    getline(cin, article);
    stolower(article);

    int m = 0;
    for(int i = 0; i < article.length(); i++)
    {
        if(article[i] != ' ' && (article[i - 1] == ' ' || i == 0))
            pos[m++] = i;
    }
    stringstream s_stream(article);
    
    int first = 0, firstpos = 0, count = 0, charcount = 0;
    int npass = 0;
    while(s_stream >> word)
    {
        if(word == key)
        {
            if(!first)
            {
                firstpos = pos[npass];
                first = 1;
            }
            count++;
        }
        npass++;
    }
    if(!first)
        printf("%s\n", "-1");
    else
        printf("%d %d\n", count, firstpos);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值