Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains a char?

Tags:

c++

stdstring

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?

like image 375
Robert Lewis Avatar asked Apr 26 '17 08:04

Robert Lewis


People also ask

How do you check if a char is in a string Python?

Using in operator The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise. ch = '. '

How do you test if a string contains a character in Java?

The Java String contains() method is used to check whether the specific set of characters are part of the given string or not. It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise. It can be directly used inside the if statement.


Video Answer


2 Answers

Look at the documentation string::find

std::string s = "hell[o"; if (s.find('[') != std::string::npos)     ; // found else     ; // not found 
like image 170
thibsc Avatar answered Oct 06 '22 23:10

thibsc


Starting from C++23 you can use std::string::contains

#include <string>  const auto test = std::string("test");  if (test.contains('s')) {     // found! } 
like image 25
Synck Avatar answered Oct 06 '22 23:10

Synck