gpt4 book ai didi

c++ - 将字符串存储在数组中以在 IF 语句中使用的可能方法

转载 作者:行者123 更新时间:2023-11-28 03:06:56 25 4
gpt4 key购买 nike

我有以下代码,它搜索任何没有 Q 后跟 U 的单词。有什么可能的方法可以压缩这段代码,以便它只使用一个 if 语句但搜索每个组合?

        if (word1.find("qq") != std::string::npos) {
cout << word1 << endl;
}
if (word1.find("qa") != std::string::npos) {
cout << word1 << endl;
}
//...

最佳答案

这个的局限性是我认为它不会捕捉到“quqa”。

 if (word1.find('q') != std::string::npos 
&& word1.find("qu") == std::string::npos)
cout << word1 << endl;

编辑:这将计算“q”的数量并确保“qu”的数量相同。我认为这可能比搜索每个文字组合更有效。

size_t stringCount(const std::string& referenceString,
const std::string& subString) {

const size_t step = subString.size();

size_t count(0);
size_t pos(0) ;

while( (pos=referenceString.find(subString, pos)) !=std::string::npos) {
pos +=step;
++count ;
}

return count;

}

bool check_qu(const std::string &word1)
{
int num_q = stringCount(word1, "q");
return (num_q > 0) ?
(stringCount(word1, "qu") == num_q) : true;
}

关于c++ - 将字符串存储在数组中以在 IF 语句中使用的可能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442472/

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