2- std::string::append()
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);
C++
// CPP program to get a string from single // character. #include<bits/stdc++.h> using namespace std; int main() { string str; str.append(1, 'G' ); cout << str << endl; } |
Output
G
How to convert a single character to string in C++?
How to convert a single character to a string object.
Examples:
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.
CPP
// CPP program to get a string from single // character. #include<bits/stdc++.h> using namespace std; string getString( char x) { // string class 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. string s(1, x); return s; } int main() { cout << getString( 'a' ); return 0; } |
Output
a
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.