Conversion of character array to a string in C++
Hey programmers, In this tutorial, let us learn how to convert the character array to string in C++. There are many ways to convert an array of characters to a string. let us learn some of them.
Method 1: Assigning of character array to string literal
To convert a character array to a string, you can directly assign the character array with a list of characters to the string variable
#include <iostream>
using namespace std;
int main() {
string str = {'C', 'O', 'D', 'E', 'S', 'P', 'E', 'E', 'D', 'Y'};
cout <<str;
}OUTPUT:
CODESPEEDY
Method 2: Append each element of the character array to a string
we can append the array of characters to the string variable character by character. This can be done by using the looping statements. Let us write a program to convert character array to string by using the for-each loop.
#include <iostream>
using namespace std;
int main() {
string str = "";
char arr[] = {'C', 'O', 'D', 'E', 'S', 'P', 'E', 'E', 'D', 'Y'};
for(char i : arr) {
str += i;
}
cout <<str;
}OUTPUT:
CODESPEEDY
Method 3: Using string.append() function
Create an empty string and append the character array to the empty string by using the append function.
#include <iostream>
using namespace std;
int main() {
string str ;
char arr[] = {'C', 'O', 'D', 'E', 'S', 'P', 'E', 'E', 'D', 'Y'};
str.append(arr);
cout <<str;
}OUTPUT:
CODESPEEDY
Method 4: By using the string constructor
The array of characters can be converted into a string by using the string constructor. We have to pass the character array as a parameter for the string constructor. Therefore, the string will contain the characters from the character array.
#include <iostream>
using namespace std;
int main() {
char arr[] = {'C', 'O', 'D', 'E', 'S', 'P', 'E', 'E', 'D', 'Y'};
string str(arr);
cout <<str;
}OUTPUT:
CODESPEEDY
Leave a Reply