Introduction
A Char is a data type that stores a character within single quotes.It has a size of exactly one byte whereas a string is a sequence of characters stored within double quotes.
Example: Char C = ‘e’
Char S = “eight”
Converting char to string is a common venture in programming.
Their conversion from one to another is done using various approaches under various circumstances.
Why do we need to convert ?
We tend to attempt such conversions when we need to perform operations or pass arguments that require strings as input instead of characters.There are many reasons why one might want to convert a char to string such as:
- Comparison: To compare a char to another string one needs to convert a char into string first then do the comparison.
- Concatenation: To concatenate one char to another string one needs to convert the char into string then concatenate it.
Different Approaches to convert char to string in C++
There are various approaches to do the conversion.
The direct 6 approaches are enlisted below as follows:
→ Using string constructor
→ Using string_stream method
→ Using string insert() function
→ Using string assign() function
→ Using push_back() function
→ Using string concatenation operators
* Using operator =
* Using operator + =
Approach 1: Using string constructor
In this method a string class fill constructor defines the string size as the first parameter and in the given size the character is filled as the second parameter.
Approach to code:
At first, the character is initialized and thereafter it is converted to a string by using the class fill constructor. This method stores the character as a string after specifying the size of the string.
Let’s understand this by a simple example.
Input : x = ‘b’
Output : s = “b”
// A C++ program to convert char to string using string constructor method
#include <iostream>
using namespace std;
{
//main method
int main()
{
//initialize the character value
char c = ‘b’;
//using string class fill constructor
string s(1,c);
//Print the string
cout << s << endl;
//return
return 0;
}
}
Output:
b
Explanation:
In this code,
-> We first initialize the char c with the character ‘b’.
-> Then using the class fill constructor character ‘b’ is stored in string s.
-> The resulting string s containing the single character “b” is then printed.
-> It is an advantageous method as it provides flexibility of character conversion of a single character to string .
Approach 2: Using string_stream method
Being a part of C++ standard library, string stream allows to perform formatted input and output operations on strings.Thus, used in the conversion of a single character to string.
Approach to code:
At first a character is initialized and added into the stream.The input is then restored into string and the following string is printed.
Let’s understand this by a simple example.
Input : x = ‘A’
Output : s = “A”
// A C++ program to convert char to string using string_stream method
#include <iostream>
#include <sstream>
using namespace std;
//main method
int main()
{
stringstream stream;
//initialize the character value and it to stream
char c = ‘A’;
stream << c;
//restore the input
string s;
stream >> s;
//Print the string
cout << s << endl;
//return
return 0;
}
Output:
A
Explanation:
In this code,
-> We first initialize the char c with the character ‘A’.
-> The character ‘A’ is then added to the stream and the character is retrieved into a string from stream.
-> It is a complex method especially while handling the error and can cause performance issues. It is a rarely used method by programmers.
Approach 3: Using string insert() function
In this method insert() function is used to insert characters in the string.
Approach to code:
At first, the character is initialized and thereafter it is converted to a string by using insert() function where the character is stored at the beginning of the empty string.
Let’s understand this by a simple example.
Input : x = ‘C’
Output : s = “C”
// A C++ program to convert char to string using insert() function
#include <iostream>
Using namespace std;
//main method
int main()
{
//initialize the character value
char c = ‘C’;
//insert the character in the string
string s;
s.insert(0,1,c);
//Print the string
cout << s << endl;
//return
return 0;
}
Output:
C
Explanation:
In this code,
-> We first initialize the char c with the character ‘C’.
-> Using insert() function character ‘C’ is then inserted at the beginning of the empty string s.
-> The resulting string s containing the single character “C” is then printed.
-> This method can be a bit slower than other methods but being a member function it’s easy to use.
Approach 4: Using string assign() function
In this method assign() function is used to replace the current value of string with character.
Approach to code:
At first, the character is initialized and thereafter it is converted to a string by using the assign() function where the character replaces the empty string.
Let’s understand this by a simple example.
Input : x = ‘d’
Output : s = “d”
// A C++ program to convert char to string using assign() function
#include <iostream>
using namespace std;
//main method
int main()
{
//initialize the character value
char ch = ‘d’;
//assign the character to the string
string s;
s.assign(1,ch);
//Print the string
cout << s << endl;
//return
return 0;
}
Output:
d
Explanation:
In this code,
-> We first initialize the char ch with the character ‘d’.
-> Using assign()function character ‘d’ is assigned to the empty string s.
-> The resulting string s containing the single character “d” is then printed.
-> This method is a good approach as it is simple and does the conversion in a single line.
Approach 5: Using push_back() function
In this method push_back() function is used to append the character to the end of the string.
Approach to code:
At first, the character is initialized and thereafter it is converted to a string by using push_back() function where the character is appended to the end of the empty string.
Let’s understand this by a simple example.
Input : x = ‘e’
Output : s = “e”
// A C++ program to convert char to string using push_back() function
#include <iostream>
using namespace std;
//main method
int main()
{
//initialize the character value
char ch = ‘e’;
//append the character to the string
string s;
s.push_back(c);
//Print the string
cout << s << endl;
//return
return 0;
}
Output:
e
Explanation:
In this code,
-> We first initialize the char ch with the character ‘e’.
-> Using push_back()function character ‘e’ is appended to the empty string s.
-> The resulting string s containing the single character “e” is then printed.
-> This method is also a good approach being simple and having single line code.
Approach 6: Using string concatenation operators
* using operator =
In this method operator = is used to to assign the string with a single character.
Approach to code:
At first, the character is initialized and thereafter it is converted to a string by assigning the character with operator = to string.
Let’s understand this by a simple example.
Input : x = ‘f’
Output : s = “f”
// A C++ program to convert char to string using concatenating operator =
#include <iostream>
Using namespace std;
//main method
int main()
{
//initialize the character value
char ch = ‘f’;
//the character is assigned to string
string s;
s = ch;
//Print the string
cout << s << endl;
//return
return 0;
}
Output:
f
Explanation:
In this code,
-> We first initialize the char ch with the character ‘f’.
-> Using operator = character ‘f’ is assigned to a string.
-> The resulting string s containing the single character “f” is then printed.
-> This method is convenient and concise to use .
* using operator + =
In this method operator += is used to append the character at the end of the string.
Approach to code:
At first, the character is initialized and thereafter it is converted to a string by appending the character to the end of the string with operator += .
Let’s understand this by a simple example.
Input : x = ‘g’
Output : s = “g”
// A C++ program to convert char to string using concatenation operator +=
#include <iostream>
using namespace std;
//main method
int main()
{
//initialize the character
char ch = ‘g’;
//the character is assigned to string
string s;
s += ch;
//Print the string
cout << s << endl;
//return
return 0;
}
Output:
g
Explanation:
In this code,
-> We first initialize the char ch with the character ‘g’.
-> Using operator += character ‘g’ is appended to an empty string.
-> The resulting string s containing the single character ‘g’ is then printed.
-> This method is also convenient, concise and readable to use .
Best Approach
I personally prefer the approach of using string constructor to convert a char into string.
Here are some points listed below that I kept in mind while choosing the best approach.
-> It has a simple syntax and an easy approach to convert the assigned character to string and is mostly preferred over any complex approach.
-> The code is user friendly as well as more convenient to use when compared to other approaches.
Sample Problems:
Sample Problem 1:
Convert the character ‘G’ to string “G” using the best approach i.e using string constructor method.
// A C++ program to convert char to string using string constructor method
#include <iostream>
using namespace std;
{
//main method
int main()
{
//initialize the character value and string
char c1 = ‘G’;
char c2 = ‘S’;
string st = ‘Gun’;
//using string class fill constructor
string s1(1,c1);
string s2(1,c2);
//Replace a character in another string
size_t index = st.find(c1);
while(index != string::npos)
{
st.replace(index, 1 ,c2);
index = st(c1,index +1);
}
cout << “ The new string is: “ <<st << endl; .
//return
return 0;
}
}
Output:
The new string is: Sun
Explanation:
In this code,
-> We first initialize the char c1 with character ‘G’ and c2 with character ‘S’ and the string st with “Gun”.
-> Then using class fill constructor characters ‘G’ and ‘S’ are stored in string s1 and s2 respectively.
-> The index of first occurrence of c1 is found in the string st using find function until the end is reached. The starting index of previous occurrence is plus 1.
-> Then the string is looped and every occurrence of c1 is replaced with c2 using the replace function.
-> The resulting replaced character string is then printed.
Sample Problem 2:
Convert the character ‘I’ to string “I” using the string_stream method and concatenate it at the end of another string.
#include <iostream>
#include <sstream>
using namespace std;
//main method
int main()
{
stringstream stream;
//initialize the character value and it to stream
string str = “Apple”
char c = ‘I’;
stream << c;
//restore the input
string s;
stream >> s;
//Concatenate the string
string st= str + s;
//Print the string
cout << s << endl;
//return
return 0;
}
Output:
AppleI
Explanation:
In this code,
-> We first initialize the char c with the character ‘I’.
-> The character ‘I’ is then added to the stream and the character is retrieved into a string from the stream.
Sample Problem 3:
Convert the character ‘L’ to string “L” using the string insert() function and use it to create a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//main method
int main()
{
//initialize the character value
char ch = ‘L’;
//assign the character to the string
string s;
s.assign(1,ch);
//to create the file
ofstream myFile(“myFile.txt”);
if(myFile.is_open())
{
myFile<< (“The file is created using :”) << s << endl;
myFile.close();
cout << “File created” << endl;
}
else {
cout << “ Unable to create file “ endl;
}
//return
return 0;
}
Output:
File created
Explanation:
In this code,
-> We first initialize the char c with the character ‘L’.
-> Using insert() function character ‘L’ is then inserted at the beginning of the empty string s.
-> The resulting string s containing the single character “L” is then used to create a file as myFile.txt.
-> The is checked whether opened or closed and then if open the char converted to string is printed otherwise error message is printed.
Sample Problem 4:
Convert the character ‘T’ to string “T” using the string assign() function and search for a substring within another string.
#include <iostream>
#include <string>
using namespace std;
//main method
int main()
{
//initialize the character value and string
char ch = ‘T’;
string st = “Tommy is a dog name”;
//assign the character to the string
string s;
s.assign(1,ch);
//Search for a sub-string and print it
size_t found = st.find(s);
if (found != string::npos)
{
cout << “Substring” << s << “ found at “ << found << endl;
}
else
{
cout << “ Substring not found” << endl;
}
//return
return 0;
}
Output:
Substring T found at 0
Explanation:
In this code,
-> We first initialize the char ch with character ‘T’ and a new string st .
-> Using assign()function character ‘T’ is assigned to the empty string s.
-> The resulting string s containing the single character “T” is then used to find the position substring T in new string st .
->If the result is found it prints the position otherwise prints the error message
Sample problem 5:
Convert the character ‘P’ to string “P” using push_back() function and use it to count the number of occurrences of the character in another string.
#include <iostream>
#include <string>
using namespace std;
//main method
int main()
{
//initialize the character value and string
char ch = ‘P’;
string t = “puppy”
//append the character to the string
string s;
s.push_back(c);
//Check the number of occurrence and print it
int count = 0;
for (int i=0; i< t.length(); i++) {
if(t.substr(i,1) == s)
{
count ++;
} }
cout << “ The character” << ch << “occurs” << count << “ times in the string.” << endl;
//return
return 0;
}
Output:
3
Explanation:
In this code,
-> We first initialize the char ch with character ‘P’ and a new string t with “ puppy”.
-> Using push_back()function character ‘P’ is appended to the empty string s.
-> The resulting string s containing the single character “P” is then used to check the occurrence of the character ‘p’ in the string t.
-> The number of occurrences of the character in the string t is then printed.
Sample Problem 6:
Convert the character ‘M’ to string “M” using concatenation operator = and use then use it to create a new string with repeated characters.
#include <iostream>
#include <string>
Using namespace std;
//main method
int main()
{
//initialize the character value
char ch = ‘M’;
//the character is assigned to string
string s;
s = ch;
//Print a new string with repeated characters
int numchars = 4;
string repeatedchars = string(numchars, ch);
cout << “ New string with repeated characters is: “ << repeated chars << endl;
//return
return 0;
}
Output:
MMMM
Explanation:
In this code,
-> We first initialize the char ch with the character ‘M’.
-> Using operator = character ‘M’ is assigned to a string.
-> An integer variable numChars is initialized with the value 5.Then string constructor is used to take two arguments to create a new string repeatedChars with numChars repeated occurrences of ch.
-> The resulting string s containing the single character “M” is then printed.
Convert the character ‘N’ to string “N” using concatenation operator += and append it to an existing string.
#include <iostream>
#include <string>
using namespace std;
//main method
int main()
{
//initialize the character and string
char ch = ‘O’;
string st = “HELL”
//the character is assigned to a new string
string s;
s += ch;
// append the string and print it
st.append(ch);
cout << “ The new string after appending is” << st << endl;.
//return
return 0;
}
Output:
The new string after appending is HELLO
Explanation:
In this code,
-> We first initialize the char ch with character ‘O’ and the string st with “ HELL”.
-> Using operator += character ‘O’ is appended to an empty string.
-> The resulting string s containing the single character ‘O’ is now appended to a new string using the append function.
Conclusion
From the above article we had an idea about how to convert a char to string using various approaches.Now you all are familiar with all the approaches and their respective syntax-es and can decide which one would be the best to use.Each approach is unique on it’s own way and has it’s own advantages and disadvantages depending upon the requirements of the program.