Reputation: 1078
I am very new to C++.
With a combination of Google and StackOverflow I have managed to write some code to check if a string contains another string.
string stringToSearch = "my foo bar";
std::string firstNeedle("foo");
std::size_t firstSearch = stringToSearch.find(firstNeedle);
if( firstSearch != std::string::npos ){
// do code here
}
This code works brilliantly. However, now I want to add another string to look for, so something like....
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
}
I'm presuming this won't work as there is nothing to indicate which string the "std::string::npos" is referring to?
I wondered how I would do this?
Or is it possible to use an array - In PHP (because I'm familiar with PHP) something like:
$stringToSearch = "my foo bar";
$arrayOfSearchTerms = array("foo", "bar");
foreach( $arrayOfSearchTerms as $singleSearchTerm ){
if( strpos( $stringToSearch, $singleSearchTerm ) !== false) {
// do code here
}
}
Upvotes: 1
Views: 659
Reputation: 311028
If I have understood correctly you can write
for ( const auto &s : { "foo", "bar" } )
{
auto pos = stringToSearch.find( s );
if ( pos != std::string::npos )
{
//...
}
}
The same can be done using variables. For example
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 )
{
//...
}
}
Here is a demonstrative program
#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;
}
Upvotes: 1
Reputation: 16876
I'm presuming this won't work
This works just fine. The way you have it, the // do code here
code will be executed if at least one of the strings was found, so if "my foo bar"
contains either "foo"
or "bar"
or both of them.
If you want it so it only works if both "foo"
and "bar"
have to be contained in the stringToSearch
, you can achieve that by changing the ||
to &&
:
if ((firstSearch != std::string::npos) && (secondSearch != std::string::npos)) {
as there is nothing to indicate which string the "std::string::npos" is referring to?
Nah, there's no issue here. (firstSearch != std::string::npos)
evaluates to a boolean value and (secondSearch != std::string::npos)
evaluates to a separate boolean value that doesn't conflict with it in any way. You can use logical operators such as &&
and ||
to work with those booleans as usual.
Upvotes: 3