gpt4 book ai didi

c++ 在另一个 std::string 中出现一个 std::string

转载 作者:行者123 更新时间:2023-11-30 02:53:52 25 4
gpt4 key购买 nike

我正在尝试计算一个 std::string 在另一个 std::string 中的出现次数:

   static int cantidadSimbolos(const std::string & aLinea/*=aDefaultConstString*/,
const std::string & aSimbolo/*=aDefaultSimbolSeparador*/)
{
if(aSimbolo.empty()) return 0;
if (aLinea.empty()) return 0;
int aResultado=0;
//This is the line that the compiler doesnt like
aResultado=std::count(aLinea.begin(),aLinea.end(),aSimbolo);
return aResultado;
}

但是编译器不喜欢它,这是编译器发出的错误:

error: no match for ‘operator==’ in ‘_first._gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* >() == __value’

有什么帮助吗?提前谢谢!

最佳答案

以下代码将查找给定字符串的非重叠出现次数。

using namespace std;

static int countOccurences(const string & line, const string & symbol) {

if (symbol.empty()) return 0;
if (line.empty()) return 0;
int resultCount = 0;

for (size_t offset = line.find(symbol); offset != string::npos;
offset = line.find(symbol, offset + symbol.length()))
{
resultCount++;
}

return resultCount;

}

int main(int argc, const char * argv[])
{
cout << countOccurences("aaabbb","b") << endl;

return 0;
}

find 函数将返回一个指向它匹配的值的第一个元素的迭代器,或者返回 'last' 因此 string::npos。这确保不与 offset + symbol.length() 重叠。

为了英语用户的可读性,我尽力将变量翻译成英语。

关于c++ 在另一个 std::string 中出现一个 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17578236/

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