我对C ++很陌生。
结合使用Google和StackOverflow,我设法编写了一些代码来检查一个字符串是否包含另一个字符串。
string stringToSearch = "my foo bar";
std::string firstNeedle("foo");
std::size_t firstSearch = stringToSearch.find(firstNeedle);
if( firstSearch != std::string::npos ){
// do code here
}
这段代码非常出色。但是,现在我想添加另一个字符串来查找,所以类似...。
string stringToSearch = "my foo bar";
std::string firstNeedle("foo");
std::size_t firstSearch = stringToSearch.find(firstNeedle);
std::string secondNeedle("bar");
std::size_t secondSearch = stringToSearch.find(secondNeedle);
if( (firstSearch != std::string::npos) || (secondSearch != std::string::npos) ){
// do code here
}
我以为这是行不通的,因为没有任何东西可以表明“ std :: string :: npos”是指哪个字符串?
我想知道我该怎么做?
还是可以使用数组-在PHP中(因为我熟悉PHP)类似:
$stringToSearch = "my foo bar";
$arrayOfSearchTerms = array("foo", "bar");
foreach( $arrayOfSearchTerms as $singleSearchTerm ){
if( strpos( $stringToSearch, $singleSearchTerm ) !== false) {
// do code here
}
}
我想这是行不通的
这样很好。你有它的方式,// do code here
如果字符串中的至少一个被发现的代码会被执行,因此,如果"my foo bar"
包含两种"foo"
或"bar"
或两者。
如果你想它,所以它只有工作,如果双方 "foo"
并"bar"
已包含在向stringToSearch
,就可以实现,通过改变||
到&&
:
if ((firstSearch != std::string::npos) && (secondSearch != std::string::npos)) {
因为没有什么可以表明“ std :: string :: npos”是指哪个字符串?
不,这里没有问题。(firstSearch != std::string::npos)
评估为布尔值,并(secondSearch != std::string::npos)
评估为与布尔值完全不冲突的单独布尔值。您可以使用逻辑运算符(例如&&
和)||
像往常一样使用这些布尔值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句