Extract a Substring from a Character Array in C++
To extract a substring from a character array in C++ follow the below approach:
Approach
- Convert the character array to std::string.
- Declare a temporary string to store the substring.
- Use the std::substring method to extract the substring.
- Store the substring in the temporary string.
C++ Program to Extract a Substring from a Character Array
The following program illustrates how we can extract a substring from a character array in C++:
// C++ Program to illustrate how to extract a substring from
// a character array
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare the character array
char arr[] = "Geeks for Geeks";
// Convert the character array to string
string str(arr);
// Print the string
cout << "String: " << str << endl;
// Extract the substring starting at index 0 which is of
// length 5.
string sub = str.substr(0, 5);
// Print the substring
cout << "Substring: " << sub << endl;
return 0;
}
Output
String: Geeks for Geeks Substring: Geeks
Time Complexity: O(N) where N is the length of the character array.
Auxiliary Space: O(N)
How to Extract a Substring from a Character Array in C++?
In C++, character arrays are used to store sequences of characters also known as strings. A substring is a part of a string that consists of a continuous sequence of characters from the string. In this article, we will learn how to extract a substring from a character array in C++.