How to Check if a Substring Exists in a Char Array in C++?
Last Updated :
08 Feb, 2024
Improve
In C++, Char array and std::string both are used to store a sequence of characters to represent textual data. In this article, we will learn how to check if a substring exists within a char array in C++.
Example
Input: charArray[]= "Hello, Geek" subString="Geek" Output: Geek substring is found in char array: Hello, Geek!
Search for a Substring in Char Array
The C++ STL provides the std::find() function to search for a given substring in a range of values.
- If the substring is found, then find() function will return the index of the first occurrence of the given substring.
- If the substring is not found, then std::string::npos (no position) is returned which indicates that the given substring does not exist in a char array.
C++ Program to Search for a Substring in Char Array
// C++ program to check if a substring is present in a char
// array
#include <iostream>
#include <string>
using namespace std;
int main()
{
// character array
char char_arr[] = "Hello, Geek!";
// substring
const char* sub_string = "Geek";
// converting character array to string using string
string char_arr_str = char_arr;
// use the find method to check substring present or not
if (char_arr_str.find(sub_string) != string::npos) {
cout << sub_string
<< " substring is found in char array: "
<< char_arr_str << endl;
}
else {
cout << sub_string
<< " substring is not found in char array: "
<< char_arr_str << endl;
}
return 0;
}
Output
Geek substring is found in char array: Hello, Geek!
Time Complexity: O(N * M), where N is the size of the char array and M is the size of the substring.
Auxiliary Space: O(1)
We can also use strstr() function to check if a substring exists in a char array or not.