如何检查一个字符串是否包含多个其他字符串?

How to check if a string contains multiple other strings?

本文关键字:字符串 是否 其他 包含多 何检查 检查 一个      更新时间:2023-10-16

我对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)计算为与其不冲突的单独布尔值。您可以使用逻辑运算符(如&&||(像往常一样使用这些布尔值。

如果我理解正确,你可以写

for ( const auto &s : { "foo", "bar" } )
{
auto pos = stringToSearch.find( s );
if ( pos != std::string::npos )
{
//...
}
}

使用变量也可以完成相同的操作。例如

string stringToSearch = "my foo bar";
std::string firstNeedle("foo");
std::string secondNeedle("bar");
for ( const auto &s : { firstNeedle, secondNeedle } )
{
auto pos = stringToSearch.find( s );
if ( pos != std::string::npos )
{
//...
}
}

这是一个演示程序

#include <iostream>
#include <string>
int main() 
{
std::string stringToSearch = "my foo bar";
std::string firstNeedle("foo");
std::string secondNeedle("bar");
for ( const auto &s : { firstNeedle, secondNeedle } )
{
auto pos = stringToSearch.find( s );
if ( pos != std::string::npos )
{
std::cout << stringToSearch.substr( pos ) << 'n';
}
}
return 0;
}