【问题标题】:How can I count number of "xxx" in string c++?如何计算字符串 C++ 中“xxx”的数量?
【发布时间】:2019-09-26 06:58:20
【问题描述】:

我想计算字符串sxxx 的数量,我试过这个:

cn2=count(s.begin(), s.end(), 'xxx'); 这就是问题所在:warning: multi-character character constant [-Wmultichar]|

然后我尝试了这个:

cn2=count(s.begin(), s.end(), "xxx");

但我们应该在count参数中输入字符。

【问题讨论】:

  • std::count 只能计算单个字符。您可以使用 std::search 编写自己的算法来执行此操作
  • @Tharwen 与 std::search?怎么样?
  • Remy Lebeau 描述了如何用 std::find 来做,非常相似
  • @ParisaMousavi 我在答案中添加了一个std::search() 示例

标签: c++ string count character


【解决方案1】:

您可以在循环中使用std::string::find(),例如:

int count = 0;
std::string::size_type pos = 0;
while ((pos = s.find("xxx", pos)) != std::string::npos)
{
    ++count;
    pos += 3;
}

std::search():

#include <algorithm>

int count = 0;
std::string sub = "xxx";
std::string::iterator iter = s.begin();
while ((iter = std::search(iter, s.end(), sub.begin(), sub.end())) != s.end())
{
    ++count;
    iter += sub.size();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多