In this C++ tutorial, you shall learn how to append a character to the beginning of a given string using Addition Operator, with example programs.
Append Character to beginning of String
To append character to beginning of a string in C++, we can use Addition Operator. Add the character and the string, and assign the result of this expression back to the string.
The syntax of the statement to append a character ch
to the beginning of the string str
is
str = ch + str;
C++ Program
In the following program, we take a string in str
, and a character in ch
. We append the character ch
to the beginning of the string str
, and print the resulting string to console output.
main.cpp
#include <iostream>
using namespace std;
int main() {
string str = "apple";
char ch = 'm';
str = ch + str;
cout << str;
}
Output
mapple
Reference
In the above program(s), we have used the following C++ concepts. The links have been provided for reference.
Conclusion
In this C++ Tutorial, we learned how to append a character to the beginning of a given string.