如何检查一个字符串是否包含多个其他字符串?
How to check if a string contains multiple other strings?
我对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;
}
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 检查字符串是否为整数
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串是否正确以将其转换为 int?
- 程序检查字符串是否只包含 1 和 0?
- 检查字符串是否是拉平德罗姆
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- gtest:检查字符串是否等于两个字符串之一
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何检查字符串是否以C++中的"ed"结尾;
- 字符串是否在其构造函数中复制数据
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何检查一个字符串是否包含多个其他字符串?
- 检查字符串是否仅包含字母
- 如何根据一个特定字母的出现来确定两个字符串是否相等?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法