c++如何用count函数求字符串B在字符串A中出现的次数。

2025-03-04 18:18:01
推荐回答(2个)
回答1:

这样是可以的。
string A("ababa");
string B("aba");
string::size_type pos = 0;
unsigned int cnt = 0;
while ((pos = A.find_first_of(B, pos)) != string::npos) {
++cnt;

++pos;

}
cnt即为出现的次数。

string A("ababa");
string B("aba");
用std::count(A.begin(), A.end(), B)试试。应该也是可以的吧。因为string有重载==运算符。

回答2:

count肯定不支持。你要用substr的函数来实现。