Data structure plays a vital role while programming your code irrespective of any language you choose to work with. While every programming language has its own set of data structures, C++ deals with quite a lot of them including strings and characters. While working with C++, there are some instances where you wish to convert character to string data structure and make your code efficient and effective. In this article, let us dive deep to look at some of the common methods by which you can easily convert char to string externally 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?
The character is a primitive data type in C++, also known as 'char' data structure. A char data structure can be stored to store a single 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. Note that the encoding format used by the character data structure in C++ is ASCII. Before you start scratching your head with what ASCII is, let us tell you that it stands for American Standard Code for Information Interchange. It defines a particular way of representing English characters as numbers. For example, the letter ‘a’ has the ASCII value 97 and ‘A’ has the ASCII value ‘65’.
For 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. Keep in mind that String is not a primitive data type in C++, rather it is a class. The string class is used to handle and manipulate strings. In technical terms, a String is a sequence of characters terminated by a null character. Not the technical person? Let's understand it in simple terms.
Consider the example of the word "Favtutor". Here, the word “FavTutor” is a string, and F, a, v, T, u, t, o, 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 null character.
For example:
#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
Relation Between Char and String
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 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. In C++, we can declare a string in two ways:
- By declaring an array of characters
- By using the String Standard Library(SSL)
How to Convert Char to String in C++
Conversion to a string object allows us to use several methods as well as its overloaded operators, which makes manipulation of strings easier. For example, 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 is 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 today 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);
For 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 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
Conclusion
The introduction of string class in C++ made the manipulation and handling of strings easier. Prior to this class, even the simple string operations involved a lot of complexity. It tells us the importance of converting a char to a string. In this article, we first discussed char and strings in brief and looked into the different methods to convert char to string in c++ externally. We highly recommend you to understand the above-discussed methods thoroughly as they are very efficient and ultimately help you make your C++ programming easy and effective. You can also take C++ homework help from our tutors who are available 24/7.