问题
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?
回答1:
Look at the documentation string::find
std::string s = "hell[o";
if (s.find('[') != std::string::npos)
; // found
else
; // not found
回答2:
If the array is char* array
or char array[]
, you can find a char
through a while
loop:
while(i < nSize)
if (array[i] == '[')
Note: '['
is the correct char literal, but "["
is a string literal.
回答3:
To check if a character of a string is equal to a particular character, you need to check in the below manner:
if(array.at(i) == '[') {
}
Check below link for more details: https://www.geeksforgeeks.org/string-at-in-cpp/##targetText=string%20at()%20in%20C%2B%2B,characters%20from%20a%20given%20string.&targetText=Syntax%202%3A,first%20character%20has%20index%200)
来源:https://stackoverflow.com/questions/43629363/how-to-check-if-a-string-contains-a-char