zoukankan      html  css  js  c++  java
  • P1308 [NOIP2011 普及组] 统计单词数

    题目传送门

    一、知识点整理

    1、字符串转小写

     //转为小写
     transform(a.begin(), a.end(), a.begin(), ::tolower);
    
    for (int i = 0; i < b.size(); i++) if (b[i] >= 'A' && b[i] <= 'Z') b[i] += 32;
    

    2、读入带空格的字符串

     //读入一行数据之前,如果有输入,要getchar();
     getchar();
     //读入b字符串
     getline(cin, b);
    

    3、查找子串

    \(string\)\(find()\)返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回一个特别的标记\(npos\)。(返回值可以看成是一个\(int\)型的数)

    string s("1a2b3c4d5e6f7jkg8h9i1a2b3c4d5e6f7g8ha9i");
    string flag;
    string::size_type position = s.find("jk");
    //find 函数 返回jk 在s 中的下标位置, 如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295,
    if (position != string::npos)
       printf("position is : %d\n" ,position);
    else 
       printf("Not found the flag\n");
    

    4、首次位置,最后一次位置

    flag = "c";
    
    position = s.find_first_of(flag);
    printf("s.find_first_of(flag) is :%d\n",position);
    
    position = s.find_last_of(flag);
    printf("s.find_last_of(flag) is :%d\n",position);
    

    5、查找某一给定位置后的子串的位置

       //从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
       position=s.find("b",5);
       cout<<"s.find(b,5) is : "<<position<<endl;
    

    6、查找所有子串在母串中出现的位置

       flag="a";
       position=0;
       int i=1;
       while((position=s.find(flag,position))!=string::npos)
        {
            cout<<"position  "<<i<<" : "<<position<<endl;
            position++;
            i++;
        }
    

    二、实现代码

    #include <bits/stdc++.h>
    
    using namespace std;
    int pos = -1;
    int cnt;
    string a, b;
    
    int main() {
        cin >> a;
        //转为小写
        transform(a.begin(), a.end(), a.begin(), ::tolower);
        //扩展为左右加空格
        a = ' ' + a + ' ';
    
        //读入一行数据之前,如果有输入,要getchar();
        getchar();
        //读入b字符串
        getline(cin, b);
        //左右加空格
        b = ' ' + b + ' ';
        //转为小写
        transform(b.begin(), b.end(), b.begin(), ::tolower);
    
        //在b中查找a
        int p = 0;
        while ((p = b.find(a, p)) != string::npos) {
            cnt++;
            if (cnt == 1) pos = p;
            p++;
        }
        if (cnt > 0) printf("%d %d\n", cnt, pos);
        else printf("%d", -1);
        return 0;
    }
    
  • 相关阅读:
    【CI】系列一:总体环境规划
    【原】Ubuntu下使用teamviewer
    [Android] android:visibility属性应用
    Android 软键盘
    android EditText inputType 及 android:imeOptions=”actionDone”
    【Android】The application has stopped unexpectedly.Please try again.
    【IntelliJ IDEA 12使用】导入外部包
    [转载]Android开发者必须深入学习的10个应用开源项目
    【android相关】【问题解决】R.java文件丢失
    1月1日起,我市交通事故快速理赔上限提高至1万元!
  • 原文地址:https://www.cnblogs.com/littlehb/p/15571003.html
Copyright © 2011-2022 走看看