C++ program to add a character at the end of the string by using push_back function

C++ program to add a character at the end of the string by using push_back function:

We can add a character at the end of a string in C++ by using the std::string::push_back method. This method takes one character as the parameter and appends the character at the end of the string.

In this post, we will learn how to append a character at the end of the string by using the push_back function.

Definition of push_back:

push_back is defined as like below:

void push_back(char c)

It takes one character c as the argument, appends it to the end of the string.

This method doesn’t return anything. It also changes the length of the string by 1.

Example of push_back:

Let’s take an example of push_back:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string givenString = "Hello World";

    cout<<"String before push_back: "<<givenString<<endl;

    givenString.push_back('!');

    cout<<"String after push_back: "<<givenString<<endl;

    return 0;
}

Here,

  • givenString is the original string.
  • We are calling push_back to add a ! and printing the string again.

If you run the above program, it will print the below output:

String before push_back: Hello World
String after push_back: Hello World!

C++ push back

We can also add multiple characters using push_back:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string givenString = "Hello World";

    cout<<"String before push_back: "<<givenString<<endl;

    givenString.push_back(' ');
    givenString.push_back('!');
    givenString.push_back('!');
    givenString.push_back('!');

    cout<<"String after push_back: "<<givenString<<endl;

    return 0;
}

It will print:

String before push_back: Hello World
String after push_back: Hello World !!!

Conclusion:

The push_back function is useful if you want to quickly add a character to the end of a string in C++. Note that it also changes the length of the string and if you doing any length related operations, you must keep that in mind if you use push_back.

You might also like: