Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Convert char* to string in C++

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

There are three ways to convert char* into string in C++.

  1. Using the “=” operator
  2. Using the string constructor
  3. Using the assign function

1. Using the “=” operator

Using the assignment operator, each character of the char pointer array will get assigned to its corresponding index position in the string.

C++




// C++ Program to demonstrate the conversion
// of char* to string using '='
#include <iostream>
using namespace std;
 
int main()
{
    // declaration of char*
    const char* ch = "Welcome to GeeksForGeeks";
    string s = ch;
    cout << s;
    return 0;
}

Output

Welcome to GeeksForGeeks

2. Using string constructor

The string constructor accepts char* as an argument and implicitly changes it to string.

C++




// C++ Program to demonstrate the conversion
// of char* to string using string constructor
#include <iostream>
using namespace std;
 
int main()
{
    const char* ch = "Welcome to GeeksForGeeks";
    string s(ch);
    cout << s;
    return 0;
}

Output

Welcome to GeeksForGeeks

3. Using the assign function

It accepts two arguments, starting pointer and ending pointer, and converts the char pointer array into a string.

C++




// C++ Program to demonstrate the conversion
// of char* to string using assign function
#include <iostream>
using namespace std;
 
int main()
{
    const char* ch = "Welcome to GeeksForGeeks";
    string str;
   
    // 24 is the size of ch
    str.assign(ch, ch + 24);
    cout << str;
    return 0;
}

Output

Welcome to GeeksForGeeks

Time complexity: O(N), as time complexity of assign() is O(N) where N is the size of the new string
Auxiliary space: O(1).


My Personal Notes arrow_drop_up
Last Updated : 27 Jan, 2023
Like Article
Save Article
Similar Reads