String push_back() function in C++

In this tutorial, we will learn about the string push_back() to add a new character at the end of the string function in C++.

So, continue reading it…

push_back() function allows us to add a new character at the end of the string and increments the length of the string by 1.

The syntax is:

string_name.push_back(char);

“char” is the new character we want to add at the end.

C++ String push_back() function

Now, let us write the code to illustrate the same. See the code below before we go forward:

#include<iostream>  
using namespace std;  
int main()  
{  
    string str = "This code is written in C++ programming languag";  
    cout<< "The original string is:\n" <<str<<"\n\n";  
    str.push_back('E');  
    cout<<"Now, after pushing the character in the string is:\n"<<str;  
    return 0;     
}

The output of the program is:

The original string is:                                                                                                        
This code is written in C++ programming languag                                                                                                                                                                                                               

Now, after pushing the character in the string is:                                                                             
This code is written in C++ programming languagE

Explanation of the code is:

In this code, first of all, we declared the original string, then we will print the original string on the screen. After that, by using push_back() function we will add the new character at the end of the string, then we print the updated string on the screen. With this example, you will be able to add a new character easily.

I hope that this will help you to solve your problem.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *