How to Find the Length of a Substring in a char Array?
Last Updated : 01 Mar, 2024
Improve
In C++, a substring is a string inside another string that is the contiguous part of the string. In this article, we will learn how to find the length of a substring in a char array in C++.
Example
Input:
str[] = "Hello, World!";
substr= "World";
Output: Length of substring World is: 5
Finding Length of Substring Within Char Array in C++
To find the length of a substring in a char array iterate through the character array and use the std::strstr() function to search for the first occurrence of a substring within a character array if the substring is found calculate its length using the std::string::length() function.
C++ Program to Find Length of Substring in a Char Array
The below example demonstrates how we can find the length of the given substring in a char array.
// C++ Program to find length of a substring in a char array
#include <cstring> // For strstr
#include <iostream>
#include <string> // For std::string
using namespace std;
// Function to find the length of a substring within a char
// array
int findLen(const char* str, const string& substr)
{
// Search for the substring in the char array
const char* found = strstr(str, substr.c_str());
if (found != nullptr) {
// If found, return the length of the substring
return substr.length();
}
else {
// If not found, return -1
return -1;
}
}
int main()
{
// Example usage
const char* str = "Hello, World!. This is GeeksforGeeks";
string substr = "World";
// Find the length of the substring
int length = findLen(str, substr);
// Output the result
if (length != -1) {
cout << "Length of the substring '" << substr
<< "': " << length << endl;
}
else {
cout << "Substring not found." << endl;
}
return 0;
}
Output
Length of the substring 'World': 5
Time Complexity: O(N), here N is the length of parent string.
Auxilliary Space: O(1)