P1308 [NOIP2011 普及组] 统计单词数
题目传送门
一、知识点整理
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 : "<
6、查找所有子串在母串中出现的位置
flag="a";
position=0;
int i=1;
while((position=s.find(flag,position))!=string::npos)
{
cout<<"position "<
二、实现代码
#include
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;
}