How to check if a string contains a char?
C++StdstringC++ Problem Overview
I have a text file that I want to read. I want to know if one of the lines contains [
so I tried :
if(array[i] == "[")
But this isn't working.
How can I check if a string contains a certain character?
C++ Solutions
Solution 1 - C++
Look at the documentation string::find
std::string s = "hell[o";
if (s.find('[') != std::string::npos)
; // found
else
; // not found
Solution 2 - C++
Starting from C++23 you can use std::string::contains
#include <string>
const auto test = std::string("test");
if (test.contains('s'))
{
// found!
}
Solution 3 - C++
I did it in this way.
string s = "More+";
if(s.find('+')<s.length()){ //to find +
//found
} else {
//not found
}
It works even if you want to find more than one character but they should be lined up together. Be sure to replace ''
with ""
:
string s = "More++";
if(s.find("++")<s.length()){ //to find ++
//found
} else {
//not found
}
Solution 4 - C++
In strings, we can use find()
to get the first occurrence (position) of the given "string"
string s = "dumm[y[";
int found = s.find('[');
cout<<"$ is present at position "<<firstOccurrence; //$ is present at position 4
if (found < str.length()) {
// char found
}
else{
// char not found
}