P1308 [NOIP2011 普及組] 統計單詞數
阿新 • • 發佈:2021-11-18
一、知識點整理
1、字串轉小寫
//轉為小寫
transform(a.begin(), a.end(), a.begin(), ::tolower);
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; }