UPC 1706: 统计单词数

1706: 统计单词数

时间限制: 1 Sec   内存限制: 128 MB
提交: 557   解决: 77

[ 提交][ 状态][ 讨论版][命题人: admin]

题目描述

一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。
现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同,如果给定单词仅是文章中某一单词的一部分则不算匹配。

输入

输入有2 行。
第1 行为一个字符串,其中只含字母,表示给定单词;
第2 行为一个字符串,其中只可能包含字母和空格,表示给定的文章。
1≤ 单词长度≤10。
1≤ 文章长度≤1,000,000。

输出

只有一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从 0 开始);如果单词在文章中没有出现,则直接输出一个整数-1。

样例输入

To
to be or not to be is a question

样例输出

2 0


#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
string toletter(int a, int b, string str)         //大写变小写
{
    for(int i=a; i<b; i++)
    {
        if(str[i] >= 'A' && str[i] <= 'Z')
            str[i] = str[i] + 32;
    }
    return str;
}
int main()
{
    int tot = 0, flag = 0, index = -1;
    string str, s, temp;
    cin >> str;
    str = toletter(0, str.size(), str);
    getchar();
    getline(cin, s);
    for(int i=0; i<s.size(); i++)
    {
        while(s[i] != ' ' && i < s.size())        //挨个提取单词
        {
            temp += s[i] ;
            i ++;
        }
        //cout << temp  << endl;
        if(toletter(0, temp.size(), temp) == str)
        {
            if(!flag)                            //记录第一个位置
                index = i-temp.size(), flag = 1;
            tot ++;
        }
        temp = "";
    }
    if(index == -1)
        cout << index << endl;
    else
        cout << tot << " " << index << endl;
}



猜你喜欢

转载自blog.csdn.net/a_thinking_reed_/article/details/79732817
UPC