【题解】Luogu1308 统计单词数

细节很多,写注释里边了。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int pos = -1;//这是第一次出现的位置
int count(string s, string word){
    //基本思路:遇到空格就匹配
    int c = 0;//计数变量
    string str;
    for(int i = 0;i < s.length();i ++){
    	if(s[i] == ' '){//匹配到空格
        	if(word == str){
            	++ c;
                if(c == 1) pos = i - word.length();//很重要哦,c == 1代表是第一次匹配,i - word.length()是他在字符串中第一次出现的位置
            }
            str = "";//清空,或者str.clean()
        }
        else str += s[i];//否则就增加
    }
    return c;
}
int main(){
    string s, word;
    cin >> word;
    s = '\n';//很重要!cin和getline在一起使用会导致第二个getline读取换行
    getline(cin, s);//给他一个换行读掉
    getline(cin, s);//正常阅读
    /*
        其实你也可以这么写:  
        getline(cin, word);
        getline(cin, s);
    */
    //大小写转换
    transform(word.begin(),word.end(),word.begin(),::tolower);
    transform(s.begin(),s.end(),s.begin(),::tolower);
    int num = count(s,word);
    if(num == 0)cout << -1;
    else cout << num;
    if(pos != -1)cout <<  ' ' << pos << endl;
}
posted @ 2020-04-07 16:59  SD!LTF  阅读(129)  评论(0编辑  收藏  举报