gpt4 book ai didi

string - 查找字符串中多次出现的子字符串 [C++]

转载 作者:行者123 更新时间:2023-12-01 12:00:46 29 4
gpt4 key购买 nike

是否有任何 STL 算法或标准方法来查找字符串中特定子字符串的出现次数?例如在字符串中:

'How do you do at ou'

字符串“ou”出现了两次。我尝试了一些带谓词和不带谓词的 STL 算法,但我发现来自 STL 的那些算法想要比较字符串的组成部分,在我的例子中是 char 但不能?比较子串。我想出了这样的事情:

str - 字符串

obj - 我们正在寻找的子串

std::string::size_type count_subs(const std::string& str, const std::string& obj)
{
std::string::const_iterator beg = str.begin();
std::string::const_iterator end = str.end();
std::string::size_type count = 0;
while ((beg + (obj.size() - 1)) != end)
{
std::string tmp(beg, beg + obj.size());
if (tmp == obj)
{
++count;
}
++beg;
}
return count;
}

谢谢。

最佳答案

#include <string>
#include <iostream>

int Count( const std::string & str,
const std::string & obj ) {
int n = 0;
std::string ::size_type pos = 0;
while( (pos = obj.find( str, pos ))
!= std::string::npos ) {
n++;
pos += str.size();
}
return n;
}

int main() {
std::string s = "How do you do at ou";
int n = Count( "ou", s );
std::cout << n << std::endl;
}

关于string - 查找字符串中多次出现的子字符串 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1839064/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com