zoukankan      html  css  js  c++  java
  • 【题解】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 = '
    ';//很重要!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;
    }
    
  • 相关阅读:
    Aoj 418 ACM 排名
    HDU 3308 LCIS
    HDU 1540 Tunnel Warfare
    HDU 4417 Super Mario
    HDU 1754 I hate it
    HDU 1166 敌兵布阵
    Codeforces 1257D Yet Another Monster Killing Problem
    Codeforces 1257D Yet Another Monster Killing Problem
    CCF CSP 201709-4 通信网络
    CCF CSP 201709-4 通信网络
  • 原文地址:https://www.cnblogs.com/sdltf/p/12654385.html
Copyright © 2011-2022 走看看