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?
Look at the documentation string::find
std::string s = "hell[o";
if (s.find('[') != std::string::npos)
; // found
else
; // not found
npos
is the value returned if no such substring is found.
Starting from C++23 you can use std::string::contains
#include <string>
const auto test = std::string("test");
if (test.contains('s'))
{
// found!
}
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
}
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
}
firstOccurrence
by found
and str
by s
, find()
would return 4, not 3. Please at least run your code and make sure it is correct before posting an answer on here, thank you!
Aug 23, 2020 at 11:10
Use find() method, but remember find() gives the position!
string str;
char letter, entered_char;
cout<<"Enter a string: ";
cin>>str;
cout<<"Enter character to be found: ";
cin>>entered_char;
//remember: find() gives the position of char
letter = str.find(entered_char);
//'letter' variable contains the position of entered_char
//if entered character is not equal to str[position found]
if(entered_char != str[letter]){
cout<<"Not found!";
} else {
cout<<"Found";
}
char
as type of letter index? Usually size_t
is used for sizes and indexes. In particular, here that would avoid narrowing conversion to char
which would result in wrong value if returned index is not representable in char
range.
Jul 25, 2022 at 13:04
size_t
, if the character is not found, your code would invoke undefined behaviour since string::find
returns string::npos
and you use it to index the string in the if
statement using string::operator[]
, which is defined behaviour only if its index is between 0 and string length (see documentation for details). You should instead just check whether the index is npos
as in the accepted answer.
Jul 25, 2022 at 13:06
'['
would be a char literal,"["
is a c string.array
?char *
,char []
,std::string
,vector<char>
, any of these containers fit into the category of this question I think. @Jabberwockystring
andchar
is not useful. Nobody searches forchar
. Thanks.