How to Compare Two Substrings in a Character Array in C++?
Last Updated : 22 Mar, 2024
Improve
In C++, character arrays are used to store a sequence of characters also known as strings. A Substring is a continuous sequence of characters within a string. In this article, we will learn how we can compare two substrings in a character array in C++.
Examples:
Input: string: "Hello World" Substring1: "Hello" Substring 2: "World" Output: Substrings are not equal.
Compare Two Substrings in a Character Array in C++
To compare two substrings in a character array in C++, we can use the std::substr() method to extract the substrings we want to compare from the character array. Then, we can compare the two substrings using the equality operator(==) .
C++ Program to Compare two Substrings in a Character Array
The following program illustrates how we can compare two substrings in a character array in C++:
// C++ Program to illustrate how we can compare two
// substrings in a character array
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Initializing a character array
char charArray[] = "GeeksforGeeks";
// Extracting substrings from the character array
string substring1 = string(charArray).substr(0, 5);
string substring2 = string(charArray).substr(8, 12);
// Compare the substrings
if (substring1 == substring2) {
cout << "The substrings are equal." << endl;
}
else {
cout << "The substrings are not equal." << endl;
}
return 0;
}
Output
The substrings are equal.
Time Complexity: O(N + K) where N is the length of the character array and K is the average length of the substring.
Auxiliary Space: O(K)