How to check if a string contains a char?

C++Stdstring

C++ 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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert LewisView Question on Stackoverflow
Solution 1 - C++thibscView Answer on Stackoverflow
Solution 2 - C++SynckView Answer on Stackoverflow
Solution 3 - C++GouravView Answer on Stackoverflow
Solution 4 - C++Akash SrinivasanView Answer on Stackoverflow