c-plus-plus
  1. c-plus-plus-char-array-to-string

C++ Program: Char Array to String

In C++, we can convert a character array to a string using various methods. One of the easiest ways is to use a string constructor that takes a char array as an argument.

Syntax

string str_name(char_array);

In the above syntax, we pass a character array as an argument to a string constructor to create a new string object.

Example

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

int main() {
   char char_array[] = "hello world";
   string str(char_array);
   cout << "String: " << str << endl;
   return 0;
}

Output

String: hello world

Explanation

In the above example, we declare a character array "char_array" and initialize it with the string "hello world". We then create a new string object called "str" by passing the char array as an argument to the string constructor. Finally, we output the new string using the cout statement.

Use

Converting a character array to a string is useful in situations where we need to manipulate strings using string functions, which are not available for character arrays.

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

int main() {
   char char_array[] = "hello world";
   string str(char_array);
   str.append(" C++");
   str.erase(5, 6);
   cout << "String: " << str << endl;
   return 0;
}

In the above example, we have converted a char array to a string and manipulated it using string functions. We first append the string "C++" to the end of the string and then erase the characters from index 5 to index 10 (which include the space and "world").

Important Points

  • A character array can be converted to a string using a string constructor that takes a char array as an argument.
  • Manipulating strings using string functions is easier than working with character arrays.
  • String objects provide a safer way to handle string data, as they automatically manage the size and memory allocation.

Summary

In summary, converting a character array to a string in C++ is a quick and easy process that can be accomplished using a string constructor. Character arrays can be manipulated as strings using string functions, which makes working with string data easier and safer.

Published on: