How to Do Case-Insensitive Search for a Substring in C++?
Last Updated :
21 Feb, 2024
A substring of a string is a contiguous sequence of characters within that string. In simpler terms, a substring is a part of a larger string that appears consecutively in it. In this article, we are going to learn how to do a case-insensitive search for a substring in C++.
Example:
Input:
original = "Hello, World!"
substring = "world"
Output:
Substring found in the original string.
Case-Insensitive Search for a Substring in C++
To do a case-insensitive search for a substring in C++, we can use the std::search() function with a custom comparator that converts the characters to be compared into lowercase using tolower() and then performs the comparison.
Syntax of std::search()
search(first1, first2, second1, second2, comp);
here,
- first1: Iterator to the beginning of the first range.
- last1: Iterator to the last of the first range.
- first2: Iterator to the beginning of the second range.
- last1: Iterator to the last of the second range.
- comp: Custom comparator.
This function will return the iterator to the first occurrence of the substring. If the substring is not found, then it will return the iterator to the end of the main string.
C++ Program to to Do Case-Insensitive Search for a Substring
C++
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
bool caseInsensitiveCharCompare( char a, char b)
{
return tolower (a) == tolower (b);
}
bool caseInsensitiveSubstringSearch( const string& str,
const string& substr)
{
auto it
= search(str.begin(), str.end(), substr.begin(),
substr.end(), caseInsensitiveCharCompare);
return it != str.end();
}
int main()
{
string str = "Hello World" ;
string substr = "WORLD" ;
bool found
= caseInsensitiveSubstringSearch(str, substr);
if (found) {
cout << "Substring found"
<< endl;
}
else {
cout << "Substring not found"
<< endl;
}
return 0;
}
|
Time Complexity: O(N * M), where N is the size of the original string and M is the size of the substring to be searched.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...