字符串中某字符(组合)的个数

求给定的字符串中有几个AK (区分大小写)。


输入数据
第一行为一个整数 
t (2≤t≤10),表示数据的组数。接下来对于每组数据: 
第一行为一个仅由大小写字母组成的字符串 
s (2≤|s|≤105)。

输出数据
对于每组数据,输出一行: 

第一行为一个整数,表示这个字符串中AK个数。

用string类型中的find方法判断某字符串中是否有“AK”。

find(str):找到返回第一个字符的索引,找不到返回-1.

#include<iostream>
#include<string>
using namespace std;

int main() {
	ios::sync_with_stdio(false); cin.tie(0);
	int num; string line;
	cin >> num;
	for (int i = 0; i < num; i++) {
		int count = 0;
		/*getline(cin, line);*/第一次用这个读的字符串......结果调试的时候发现输入num,还没来得及输入字符串,line已经是空串了。
		cin >> line;
		int llength = line.length();
		while (line.find("AK") != -1) {
			int newpos = line.find("AK") + 2;
			line = line.substr(newpos, llength - newpos);
			count++;
		}
		cout << count << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/gulaixiangjuejue/article/details/80065304