Convert Char Array to String in C++

In this article, we are going to learn how to convert Char Array to String in C++. We will learn different ways to do this conversion

  • Using std::string Class Constructor to Convert Char Array to String.
  • Using memmove() Function to Convert Char Array to String.
  • Using std::basic_string::assign Method to Convert Char Array to String

1. Using std::string Class Constructor


We can create a string from a c-style character string, by using a simple std::string class constructor. We can pass the c-style string to the String class constructor as an argument and it will assign this to a std::string variable. This is the in-built implementation of the String class constructor. Let us understand this with the below example:

#include <iostream>
#include <string>
using namespace std;

int main() 
{

    const char* cstr = "Welcome to DevEnum.com tutorials";
	string str(cstr);
    cout <<"The string is: " <<str << endl;
    return 0;
}

Output

The string is: Welcome to DevEnum.com tutorials

2. Using memmove() Function


In this example, we are making use of the pointers. We are assigning the starting index pointer using the memmove() function.

 #include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main() 
{
    const char* cstr = "Welcome to DevEnum.com tutorials";
    size_t len = strlen(cstr);

    string str(len, 1);
    memmove(&str[0], cstr, len);
    cout <<"The string is: " <<str << endl;
}

Output

The string is: Welcome to DevEnum.com tutorials

3.Use std::basic_string::assign Method to Convert Char Array to String


In this example, we are making use of the std::string assign function and strlen function. This will assign the char array to a string.

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main() 
{
    const char* cstr = "Welcome to DevEnum.com tutorials";
    string str;
	size_t len = strlen(cstr);

    str.assign(cstr, len);

    cout <<"The string is: " <<str << endl;

    return 0;
}

Output

The string is: Welcome to DevEnum.com tutorials