This tutorial will discuss about a unique way to check if char array contains a char in C++.
To check if a char contains a specific character, iterate over all the characters of char array and check if any character matches with the given character. As soon as a match is found, break the loop and mark that the specified char array contains the specified character.
We have created a separate function to check if a char array contains a character,
// Check if a char array contains a character bool contains( const char * arr, size_t len, const char& ch) { bool result = false; // Iterate over the char array for(int i = 0; i < len; i++) { // Check if element at ith index in array // is equal to the given character if (arr[i] == ch) { // Match found result = true; break; } } return result; }
We can use this function to directly check if char array contains a character or not.
Let’s see the complete example,
Pointers in C/C++ [Full Course]
#include <iostream> #include <string.h> // Check if a char array contains a character bool contains( const char * arr, size_t len, const char& ch) { bool result = false; // Iterate over the char array for(int i = 0; i < len; i++) { // Check if element at ith index in array // is equal to the given character if (arr[i] == ch) { // Match found result = true; break; } } return result; } int main() { char mainStr[50] = "This is a sample text"; char ch = 'x'; // Get the numberof characters in char array size_t len = strlen(mainStr) ; // Check if Char Array contains a character if(contains(mainStr, len, ch)) { std::cout<<"Char Array contains the specific character \n"; } else { std::cout<<"Char Array does not contains the specific character \n"; } return 0; }
Output :
Char Array contains the specific character
Summary
Today we learned about several ways to check if char array contains a char in C++. Thanks.