Data structure plays a vital role while programming your code irrespective of any language you choose to work with. There are some instances where you wish to convert characters to string data structure and make your code efficient. In this article, let us look at various methods to easily convert char to string in C++, along with its corresponding examples and output.
But before getting started, let's take a short recap of string and char in C++.
What is Char in C++?
The char is a primitive data type in C++ that is used to store to store a character whether it be the alphabet, special character, numbers, escape sequence, etc. It is the data structure that occupies only a single byte of memory, however, you can also store the character as an integer internally. Here is an example:
#include using namespace std; int main() { // declare a char char ch; //input char value cin>> ch; //display ch value cout<<ch; }
Output:
g g
What are Strings?
The string is a class present in the Standard C++ Library that is used to handle and manipulate strings. Note that it is not a primitive data type of programming language. You can also say that a string is a sequence of characters terminated by a null character.
Consider the example of the word "Favtutor". Here, the word “FavTutor” is a string, and F, a, v, T, u, t, o, and r individually are characters. Conventionally, the end of a string is marked by the presence of a special character: null character(‘\0’).
It means that the string “FavTutor” is internally stored as ‘F’, ’a’, ’v’, ’T’, ’u’, ’t’, o’, ’r’, ’\0’. The length of a string is equal to the number of characters present in it and one extra space to store a null character.
Here is an example to understand it better:
#include #include using namespace std; int main() { // declare a string string str; //input string value cin>> str; //display str value cout<<str; }
Output:
Favtutor Favtutor
If you are familiar with the C language then you may know that a string is essentially an array of char data types. This concept is applicable in C++ as well. So when we say that a String is a sequence of characters terminated by a null character what we mean is that a string is an array of char data types.
How to Convert Char to String in C++?
Imagine if we had stored a string using a char array then to find the length of the string we would have to either run a loop or divide the size of the array with the size of an individual element. This task is simplified if we make use of the String class.
The String class contains a method called "length". This method when applied to a String object returns the length of the string stored by that particular object. Just like this, there are many other benefits of the String class and therefore, let us look at some of the common methods to convert char to string and have a detailed overview of the String class.
1) Using String class constructor
A constructor is a function, specific to a class, that gets called whenever an object of that class is created. The String class has several overloaded constructors. Out of all those constructors, the constructor which of particular use to us is this one:
string (size_t n, char c);
This constructor is called the fill constructor. It is named so because creating a string using this constructor fills it with n consecutive copies of character c. For example:
#include #include using namespace std; int main() { char ch = 'T'; // passing 1 as n string str1(1, ch); // passing 2 as n string str2(2, ch); // printing both the strings cout<<str1<<endl<<str2; }
Output:
T TT
As it must be clear from the above code, the n argument is for the number of times we want the character ch to be copied into the string.
2) Using string class operator =
Most operators are overloaded in the string class to make them work in accordance with strings. Overloading an operator allows them to perform other operations apart from the basic or default operation. The string class contains 3 overloaded definitions for the assignment operator. The one which we will be using here is:
string& operator= (char c);
This operator assigns a new character c to the string by replacing its current contents. For example:
#include #include using namespace std; int main() { char ch = 'T'; // declaring a string string str; // assigning a character to the String str = ch; //printing the str after assignment cout<<str; }
Output:
T
3) Using string class operator +=
The ‘+=’ operator is a combination of two operators: the addition operator and the assignment operator. We have already discussed in the previous section how the assignment operator is overloaded for characters in the string class.
Similarly, the addition operator is also overloaded and performs the function of appending. Now recall, in the case of integer and float, C++ provides us with a concise way of writing the following statement.
A = a + b
The above statement can be written in the following manner.
A += B
This same syntax is allowed with strings. Now, using this syntax we will convert a character to a string. For example:
#include #include using namespace std; int main() { char ch = 'T'; // declaring a string string str; // appending ch to str // then storing the result into str str += ch; //printing the string cout<<str; }
Output:
T
We will now understand what the statement “str += ch;“ is doing. Firstly, the string str is appended with the value stored by ch. The resulting string is then stored in the str variable.
Looking at the above example, you must have understood that "str += ch" represents the condition where "str" is appended with the value stored by "ch". Later, the resulting string is eventually stored in the str variable.
4) Using string::append()
This function does similar to what the ‘+=’ operator did in the previous section. But this function has one advantage over the ‘+=’ operator. To understand the advantage first look at the method signature:
string& append (size_t n, char c);
This method takes two arguments: char c and n. It appends n consecutive copies of character c to string upon which it was called. Whereas if we had used the += operator, then we could have only appended one character. For example:
#include #include using namespace std; int main() { char ch = 'T'; // declaring two strings string str1; string str2; // passing 1 as n str1.append(1, ch); //passing 2 as n str2. append(2,ch); //printing the string cout<<str1<<endl<<str2; }
Output:
T TT
Let us now understand the intuition behind this approach. When we declare a string it gets initialized to some null or no value. So, when we append a character to the newly declared string, then only the character is stored by the string.
This happens because the string originally doesn’t contain any value and adding any value to the null value will result in the value itself. As a result, the char is converted to the string.
5) Using string::assign()
The assign() function does what the ‘=’ operator does for strings, It assigns a new character to the string by replacing its current contents. This method like the append() method allows us to assign multiple copies of a character to the string. The method signature of the string is
string& assign (size_t n, char c);
This method replaces the current value of the string with n consecutive copies of character c. For example:
#include #include using namespace std; int main() { char ch = 'T'; // declaring two strings string str1; string str2; // passing 1 as n str1.assign(1, ch); //passing 2 as n str2. assign(2,ch); //printing the string cout<<str1<<endl<<str2; }
Output:
T TT
6) Using string::push_back()
This method appends a character to the end of the string and increases the length of the string by 1. The method syntax is as follows:
void push_back (char c);
Here is an example:
#include #include using namespace std; int main() { char ch = 'T'; // declaring a string string str; // using the push_back() function str.push_back(ch); //printing the string cout<<str; }
Output:
T
7) Using stringstream
To understand this approach we need to be familiar with the stream concept. Streams in programming is somewhat of a high-level concept, but we will try to simplify it for you.
Our code is able to read input from the keyboard and display output on the console via streams. Think of streams as a pipe. Using these pipes, our program can even read a file. The cout and cin objects, that we often use in our C++ programs are nothing but objects connected to the standard input and output streams.
The stringstream class allows us to create objects specifically for operating on strings. These objects use a string buffer that stores a sequence of characters.
In this approach, we first create a stringstream object. After that, we insert our character into the string buffer using the stringstream object created earlier. Later we empty the string buffer into an empty string. The string now contains the contents of the character and hence, the character is converted into a string. For example:
#include #include #include using namespace std; int main() { char ch = 'T'; // declaring a string string str; // creating a stringstream object stringstream stream; // adding ch to buffer stream << ch; // empty the buffer into a string stream >> str; //printing the string cout<<str; }
Output:
T
8) Using std::string::insert function
In C++, the std::string::insert function can be used to insert characters or strings into an existing string object at a pre-specified location. Depending on the type of insertion, C++ has several different types of overloads, such as
- string& insert(size_t pos, const string& str); // Inserts the string str into the original string object at position pos
- string& insert(size_t pos, const char* str); // Inserts the C-style string str into the original string object at position pos
- string& insert(size_t pos, const string& str, size_t subpos, size_t sublen); // Inserts a substring of the string str starting at position subpos and length sublen into the original string object at position pos
- string& insert(size_t pos, const char* str, size_t n); // Inserts the first n characters of the C-style string str into the original string object at position pos
- string& insert(size_t pos, size_t n, char c); // Inserts n copies of character c into the original string object at position pos
- iterator insert(const_iterator p, char c); // Inserts character c before the iterator p in the original string object
Here, ‘pos’ refers to the specific position at which the new characters or strings ‘str’ are to be inserted, ‘subpos’ is the starting position of the string to be inserted, ‘sublen’ is the length of the string, ‘n’ is the number of characters to be inserted and ‘c’ is the character to be inserted.
Here is an example code snippet showing how to convert a char to a string using the std::string::insert function:
#include #include int main() { char c = 'a'; std::string str = "hello"; int pos = 3; // position to insert char into string std::string charToString(1, c); // create a new string from the char str.insert(pos, charToString); // insert the string at the specified position std::cout << "Original string: " << "hello" << std::endl; std::cout << "New string: " << str << std::endl; return 0; }
Output:
Original string: hello New string: helalo
In this example, we first declare the char variable c and assign the value 'a' to it. We also declare the std::string variable str and assign it the value "hello". We then declare the integer variable pos to specify the position of the string to which we want the char.
We then create a new string object charToString using a constructor that accepts two arguments: the first argument is the number of characters to add to the string, which in this case is one, and the second argument is the character itself.
Finally, we call the std::string::insert function on the original string str, passing pos and charToString as arguments to insert the string. The resulting string is then printed to the console.
Using the std::string::insert function with a char value, we can easily convert a single character to a string in C++.
9) Using std::string::replace function
In C++, the std::string::replace function can be used to convert a single character of type char into a string by replacing a substring of an existing string object with another substring.
Depending on the type of insertion, C++ has several different types of overloads, such as:
- string& replace(size_t pos, size_t len, const string& str); - Replaces len characters of the original string object starting from position pos with the string str
- string& replace(const_iterator first, const_iterator last, const string& str); - Replaces the characters in the range [first, last) of the original string object with the string str
- string& replace(size_t pos, size_t len, const char* str); - Replaces len characters of the original string object starting from position pos with the C-style string str
- string& replace(const_iterator first, const_iterator last, const char* str); - Replaces the characters in the range [first, last) of the original string object with the C-style string str
- string& replace(size_t pos, size_t len, const string& str, size_t subpos, size_t sublen); - Replaces len characters of the original string object starting from position pos with the substring of the string str starting at position subpos and length sublen
- string& replace(size_t pos, size_t len, const char* str, size_t n); - Replaces len characters of the original string object starting from position pos with the first n characters of the C-style string str
- string& replace(size_t pos, size_t len, size_t n, char c); - Replaces len characters of the original string object starting from position pos with n copies of character c
- iterator replace(const_iterator first, const_iterator last, size_t n, char c); - Replaces the characters in the range [first, last) of the original string object with n copies of character c
Here, ‘pos’ is the starting position of the substring to be replaced, ‘len’ is the length of the substring to be replaced, ‘str’ is the string to be used as the replacement, ‘subpos’ is the starting position of the substring in the string, ‘sublen’ is the length of the substring to be used as the replacement, ‘n’ is the number of characters to replace, and finally, ‘c’ is the character to be used as the replacement.
The std::string::replace function returns a reference to the modified string object, allowing for chaining multiple replacements together. Here's an example code snippet that demonstrates how to convert a char to a string using the std::string::replace function:
#include #include int main() { char c = 'a'; std::string str = "hello"; int pos = 3; // position to replace char in string std::string charToString(1, c); // create a new string from the char str.replace(pos, 1, charToString); // replace the character at the specified position with the new string std::cout << "Original string: " << "hello" << std::endl; std::cout << "New string: " << str << std::endl; return 0; }
Output:
Original string: hello New string: helao
In this example, we first declare the char variable c and assign the value 'a' to it. We also declare the std::string variable str and assign it the value "hello". We then declare an integer variable pos to specify the position we want to replace the char with string.
We then create a new string object charToString using a constructor that accepts two arguments: the first argument is the number of characters to add to the string, which in this case is one, and the second argument is the character itself
Finally, we call the std::string::replace function on the original string str, using pos, 1 (to replace a single character), and charToString as arguments to replace the string with another string and print it the resulting string to the console.
Using the std::string::replace function with a char value, we can easily convert a single character to a string in C++.
Conclusion
Now you know various ways to convert char to string in C++ externally. We highly recommend you understand the above-discussed methods thoroughly. Different methods can be used at different scenarios, so you need to use them accordingly.