Append a char to the end of a string in C++
In this quick article, we’ll explore various methods to append a char at the end of a string in C++.
1. Using push_back() function
The recommended approach is to use the standard push_back() function, which is overloaded for chars and appends a character to the string’s end.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s.push_back(ch); std::cout << s; return 0; } |
2. Using += operator
We can also use the string::operator+=, which is overloaded for chars and internally calls to the push_back() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s += ch; std::cout << s; return 0; } |
3. Using append() function
Another plausible approach is to use the append() function to append a single copy of a character at the end of the string, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s.append(1, ch); std::cout << s; return 0; } |
4. Using std::stringstream function
Another good alternative is to use a string stream to convert between strings and other numerical types.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "C+"; char ch = '+'; std::stringstream ss; ss << s << ch; ss >> s; std::cout << s; return 0; } |
5. Using insert() function
Finally, we can also use the insert() function to insert a single copy of a character at the specified position in the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s.insert(s.length(), 1, ch); std::cout << s; return 0; } |
That’s all about appending a char to the end of a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)