如果标题有点含糊,首先道歉。我是 C++ 的新手,仍在努力理解该语言的复杂性。
基本上,我正在处理大量单词(实际上是字典),我将它们存储为一个 vector 。
我对此的思考过程是,我想找到所有带有“c”的单词。每次出现一个带有“c”的单词时,看看它后面是否有一个“h”。如果确实如此,则返回该词为假。希望得到这样的话:
-carbon
-carry
etc etc
到目前为止,我已尝试实现一些代码,这是我目前所拥有的:
bool hasCWithNoH(string wordName)
{
if (wordName.find('c'))
{
if (wordName.find('ch'))
{
return false;
}
}
}
在主{}源文件中由此调用:
void findCWithNoH()
{
cout << "List of words found with a 'c' but with no following 'h': " << endl;
for (Word word : words)
{
string testWord = word.getName();
if (word.hasCWithNoH(testWord))
{
cout << testWord << endl;
}
}
}
结果是这样的:
czarowitz
czech
czechic
czechoslovakian
czechs
h
ha
haaf
haak
haar
habeas-corpus
habenaria
结果找到以“c”和“h”开头的每个单词(不是我想要的)。
我认为我没有正确使用 find() 函数和循环,我能否就如何设置该函数以及 find() 函数是否是正确使用的函数提供一些建议?
如果需要更多解释,请发表评论,我可以进一步阐述。
最佳答案
Note:
Assuming for all occurrences of 'c' there shouldn't be 'h' after it, this should work.
不存在 c 时不返回 false 请查看string::find对于它的返回值
Return Value The position of the first character of the first match. If no matches were found, the function returns string::npos.
将您的功能更改为
bool hasCWithNoH(string &wordName)
{
if (wordName.find('c')!=string::npos)
{
if (wordName.find("ch")!=string::npos)//Also use double quotes for string "ch"
{
return false;
}
else
{
return true;
}
}
else
{
return false; //Because word does not contain c.
}
}
关于C++:在字符串中查找一个字符,然后在前一个字符之后查找另一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569143/