Open In App

How to Check if a Substring Exists in a Char Array in C++?

Last Updated : 08 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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


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.


Next Article
Practice Tags :

Similar Reads