check if char in string c++
Certainly! Here's an example in C++ that checks if a character is present in a string:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
char ch = 'o';
bool found = false;
for (char c : str) {
if (c == ch) {
found = true;
break;
}
}
if (found) {
std::cout << "Character '" << ch << "' is present in the string." << std::endl;
} else {
std::cout << "Character '" << ch << "' is not present in the string." << std::endl;
}
return 0;
}
Explanation:
#include <iostream>
and#include <string>
: These lines include necessary libraries for input/output and string handling.std::string str = "Hello, World!";
: Defines a string variable namedstr
and initializes it with the value "Hello, World!".char ch = 'o';
: Declares a character variablech
and assigns it the value'o'
, which is the character we want to search for in the string.bool found = false;
: Initializes a boolean variablefound
tofalse
to keep track of whether the character is found in the string.for (char c : str) { ... }
: Iterates through each characterc
in the stringstr
.if (c == ch) { found = true; break; }
: Checks if the current characterc
is equal to the characterch
we're searching for. If it is, setsfound
totrue
and breaks out of the loop.The program then checks the value of
found
. Iffound
istrue
, it prints a message indicating that the character is present in the string. Iffound
remainsfalse
after the loop, it means the character is not present in the string, and it prints a corresponding message.