There are three ways to convert char* into string in C++.
- Using the “=” operator
- Using the string constructor
- 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++
#include <iostream>
using namespace std;
int main()
{
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++
#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++
#include <iostream>
using namespace std;
int main()
{
const char* ch = "Welcome to GeeksForGeeks";
string str;
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).
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
27 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...