String 寻找ab出现次数

#include <string>
#include <iostream>

using namespace std;

int main()
{
	string str = "fabcdabxxabxxxcxab";
	int len = str.length();
	//寻找ab出现的次数
	int index = 0;//ab出现的位置
	int cnt = 0;//ab出现的次数
	while (index != string::npos)
	{
		index = str.find("ab", index);
		if (index == -1) break;//找不到退出
		str.replace(index, 2, "ABC");//找到后替换,先删除从index开始的几个字符后替换成相应的字符
		str.erase(index + 1, 1);//删除“ABC”中的B
		cout << index << " ";
		index += 1;
		cnt++;
		cout << cnt << endl;
	}
	cout << str << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34068766/article/details/82526549