Does String Contain
if (s1.find(s2) != std::string::npos)
cout << "String found!" << endl;
Do Strings Match
if (my_string1.compare(my_string2) == 0) //0=strings are the same
{
//Strings match
}
Does String Start With
if (CommandResult.find("abc") == 0)
Find first occurrence
string s1 = "hello world";
if (s1.find(' ') != string::npos)
{
cout << "Space found " << endl;
}
else
{
cout << "No spaces found" << endl;
}
If you want to know where it was found:
string s1 = "hello world";
size_t find_result;
if ((find_result = s1.find(' ')) != string::npos)
{
cout << "Space found at character " << find_result << endl;
}
else
{
cout << "No spaces found" << endl;
}
Find last occurance
string s1 = "hello 12";
size_t find_result;
if ((find_result = s1.rfind(' ')) != string::npos) //Searches from the end but still returns an index from the start of the string
{
cout << "Space found at character " << find_result << endl;
}
else
{
cout << "No spaces found" << endl;
}
