Tutorial

Convert String to Char Array and Char Array to String in C++

Published on August 3, 2022
author

Safa Mulani

Convert String to Char Array and Char Array to String in C++

In this article, we will be focusing on the different ways to convert String to char array and char array to String in C++. While dealing with String data, we may need to convert the string data items to character array and vice-versa. This tutorial will help you solve exactly that.


Convert String to Char Array in C++

C++ provides us with the following techniques to convert a string to char array:

  • Using c_str() and strcpy() function
  • Using a for loop

1. The c_str() and strcpy() function in C++

C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily.

The c_str() method represents the sequence of characters in an array of string followed by a null character (‘\0’). It returns a null pointer to the string.

Syntax:

string-name.c_str();
  • At first, we use c_str() method to get all the characters of the string along with a terminating null character.
  • Further, we declare an empty array of type char to store the result i.e. result of the conversion of string to char array.
  • Finally, we use strcpy() method to copy the character sequence generated by the c_str() method to the empty char array.

Example:

#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	 
	string str = "";
	cout<<"Enter the string:\n";
	
	cin>>str;

	char arr[str.length() + 1]; 

	strcpy(arr, str.c_str()); 
    cout<<"String to char array conversion:\n";
	for (int i = 0; i < str.length(); i++) 
		cout << arr[i]; 

	return 0; 
} 

Output:

Enter the string:
JournalDev
String to char array conversion:
JournalDev

2. String to Char Array Conversion in C++ Using for Loop in

For the conversion of char array to a string, we can use C++ for loops with ease.

  • Initially, we create an empty array of type char
  • After this, we iterate through the input string
  • While iterating, we store the characters into the char array

Example:

#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	 
	string str = "";
	cout<<"Enter the string:\n";
	
	cin>>str;

	char arr[str.length() + 1]; 
    cout<<"String to char array conversion:\n";
    for (int x = 0; x < sizeof(arr); x++) { 
        arr[x] = str[x]; 
        cout << arr[x]; 
    } 

	return 0; 
} 

Output:

Enter the string:
JournalDev
String to char array conversion:
JournalDev

Convert Char Array to String in C++

The mentioned techniques can be used to convert a char array to string in C++:

  • The ‘+’ operator
  • C++ overloaded ‘=’ operator
  • C++ inbuilt-constructor

1. C++ ‘+’ operator

C++ provides us with '+' operator to concatenate or add data items to a variable.

  • We create a new empty string to store the result.
  • Taking it ahead, we use a for loop to traverse through the input char array.
  • In the process of traversing through the array, we use ‘+’ operator to concatenate the characters to the string.

Example:

#include <bits/stdc++.h> 
using namespace std; 


int main() 
{ 
	char arr[] = { 'J', 'O', 'U', 'R', 'N', 'A', 'L', 'D', 'E', 'V' }; 
	
	int size_arr = sizeof(arr) / sizeof(char); 
	string str = ""; 
	for (int x = 0; x < size_arr; x++) { 
		str = str + arr[x]; 
	} 
	cout<<"Converted char array to string:\n";
	cout << str << endl; 
	return 0; 
} 

Output:

Converted char array to string:
JOURNALDEV

2. C++ overloaded ‘=’ operator

C++ has got the concept of overloading which makes an operator perform other operations apart from the basic or default operation.

  • Initially, we create a new empty string.
  • We use the overloaded '=' operator to store the data items character by character into the newly created empty string.

Example:

#include <bits/stdc++.h> 
using namespace std; 


int main() 
{ 
	char arr[] = { 'J', 'O', 'U', 'R', 'N', 'A', 'L', 'D', 'E', 'V' }; 
	
	int size_arr = sizeof(arr) / sizeof(char); 
	string str = ""; 
	str = arr;
	cout<<"Converted char array to string:\n";
	cout << str << endl; 
	return 0; 
} 

Output:

Converted char array to string:
JOURNALDEV

3.C++ String inbuilt constructor

In the context of conversion of char array to string, we can use C++ String Constructor for the same.

Syntax:

string string-name(char array-name);

This constructor takes a sequence of characters terminated by a null character as an input parameter.

Note: This constructor string string() can be used only at the time of string declaration throughout the program.

Example:

#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	char arr[] = { 'J', 'O', 'U', 'R', 'N', 'A', 'L', 'D', 'E', 'V' }; 
	int size_arr = sizeof(arr) / sizeof(char); 
	string str(arr);
	cout<<"Converted char array to string:\n";
	cout <<str<< endl; 
	return 0; 
} 

Output:

Converted char array to string:
JOURNALDEV

Conclusion

In this article, we have understood various techniques to convert string to char array and vice-versa in C++.


References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Safa Mulani

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 2, 2020

Example (1) doesnt compile with visual studio 2019. Error type: error C2131: expression did not evaluate to a constant 1>C:\Users\tmcla\source\repos\ConsoleApplication35\ConsoleApplication35.cpp(12,24): message : failure was caused by call of undefined function or one not declared ‘constexpr’ 1>C:\Users\tmcla\source\repos\ConsoleApplication35\ConsoleApplication35.cpp(12,24): message : see usage of ‘std::basic_string<char,std::char_traits,std::allocator>::length’ must have a constant value. How can I rewrite this to a successful compile? Would a vector construction work better?

- Terrence McLaughlin

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.