How to convert a single character to string in C++?
How to convert a single character to a string object.
Input : x = 'a' Output : string s = "a" Input : x = 'b' Output : string s = "b"
The idea is to use string class which has a constructor that allows us to specify size of
string as first parameter and character to be filled in given size as second parameter.
This is called Class-fill constructor.
// Create a string of size n and fill // the string with character x. string s(size_t n, char x);
NOTE- size_t is typedef of unsigned long long hence we should not pass negative parameters.
However there are many other ways by which you can convert character into string. The method mentioned above only works while initialization of string instance.
1- using =/+= operator
This is very Basic method and these operators are overloaded to assign or append a character.
This method is just similar as += operator discussed above but It gives us another advantage. By using this method we can append as many characters we want.
// appends n copy of character x at end of string string s(size_t n, char x);
This method is just similar as = operator discussed above but It gives us another advantage. By using this method we can append as many characters we want.
// assigns n copy of character x to the string string s(size_t n, char x);
This method is probably more rare in use. I personally don’t prefer this method until and unless I have wide use of it. For example you can use it if your program has multiple conversions such as string to int, floats etc.
Using a string literal is another way to convert a single character to a string in C++.
The basic syntax is as follows:
string str = string(1,c);
Where ‘c’ is the character to be converted. The string constructor is called with an argument of 1 and the character to create a string with that character.
Below is the demonstration of above method:
Character: G String: G
These were some methods where we can get char from string. However there are many more methods such as use of replace, insert method but that is unnecessary and quite rare.
Please Login to comment...