Open In App

How to Extract a Substring from a Character Array in C++?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++.

Extract a Substring from a Character Array in C++

To extract a substring from a character array in C++ follow the below approach:

Approach

  1. Convert the character array to std::string.
  2. Declare a temporary string to store the substring.
  3. Use the std::substring method to extract the substring.
  4. 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++
// 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)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads