Open In App

Convert char* to std::string in C++

Last Updated : 16 Oct, 2024
Comments
Improve
Suggest changes
5 Likes
Like
Report

Strings are generally represented as an instance of std::string class in C++. But the language also supports the older C-Style representation where they are represented as array of characters (char* or char[]) terminated by null character '\0'. In this article, we will learn how to convert the char* into std::string in C++.

Following are the 5 different ways to convert char* to std::string in C++:

Using Assignment Operator (=)

In C++, the easiest method to convert char* (C-style string) to a std::string is by simply assigning it to the std::string object using (=) assignment operator.

Example


Output
Welcome to GeeksForGeeks

Using std::string Constructor

We can also create an instance of std::string using the char* (C-style string) by passing it to the std::string constructor at the time of its declaration.

Example


Output
Welcome to GeeksForGeeks

Using string::assign() Method

Apart from the above methods, we can also convert the char* (character array) to std::string using std::assign() method.

Syntax

str.assign(first, last);

where first and last the pointer to the first character and the character after the last character of char* string (not considering the null character).

Example


Output
Welcome to GeeksForGeeks

Using std::copy with std::back_inserter()

C++ STL provides the std::copy() method that works well for both iterators and pointers. So, we can use this method to copy the content of char* string to std::string. We may need to use std::back_inserter() method for copying in std::string as std::copy() method does not allocate new space in the destination container.

Example


Output
Welcome to GeeksForGeeks


Manually Using string::push_back()

It is the manual method to convert char* to std::string by pushing all the characters of the char* one by one to the std::string object.

Example


Output
Welcome to GeeksForGeeks



Next Article

Similar Reads