Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
std::basic_string::operator[] in C++
Next article icon

std::string::push_back() in C++

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::string::push_back() method in C++ is used to append a single character at the end of string. It is the member function of std::string class defined inside <string> header file. In this article, we will learn about std::string::push_back() method in C++.

Example:

C++
// C++ Program to illustrate how to use // std::string::push_back() method #include <bits/stdc++.h> using namespace std;  int main() {     string s = "Geek";      // Appending character to the string     s.push_back('s');      cout << s;     return 0; } 

Output
Geeks

string::push_back() Syntax

s.push_back(c);

where s the name of the string.

Parameters

  • c: Character to append.

Return Value

  • This function does not return any value.

Note: This function only works for C++ Style strings i.e. instances of std::string class and doesn’t work for C-Style strings i.e. array of characters.

Complexity Analysis

The std::string container is generally implemented using dynamic arrays. So, std::string::push_back() function basically adds a character to the end of the internal dynamic array.

Now, with dynamic arrays, if they have enough space, then the insertion at the end is fast O(1), but if they don’t have enough space, then a reallocation might be needed, and it may take O(n) time. But the algorithm used for reallocation adjust the overall complexity to bring it to the amortized constant.

Time Complexity: O(1), Amortized Constant
Auxiliary Space: O(1)

More Examples of string::push_back()

The following examples illustrate the use of string::push_back() method is different cases.

Example 1: Constructing Whole String using string::push_back()

C++
// C++ program to construct whole string using // string::push_back() method #include <bits/stdc++.h> using namespace std;  int main() {     string s;          // Constructing string character by character     s.push_back('H');     s.push_back('e');     s.push_back('l');     s.push_back('l');     s.push_back('o');          cout << s;     return 0; } 

Output
Hello

Example 2: Creating a Pattern using string::push_back() in Loop

C++
#include <iostream> #include <string> using namespace std;  int main() {     string s = "*";          // Append '-' and '*' alternatively     for (int i = 0; i < 5; ++i) {         s.push_back('-');         s.push_back('*');     }          cout << s << endl;     return 0; } 

Output
*-*-*-*-*-* 


Next Article
std::basic_string::operator[] in C++

S

Sakshi Tiwari
Improve
Article Tags :
  • C++
  • cpp-string
  • cpp-strings-library
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • Vector push_back() in C++ STL
    In C++, the vector push_back() is a built-in method used to add a new element at the end of the vector. It automatically resizes the vector if there is not enough space to accommodate the new element. Let’s take a look at an example that illustrates the vector push_back() method: [GFGTABS] C++ #incl
    2 min read
  • std::basic_string::at in C++
    Returns a reference to the character at the specified location pos. The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not. Syntax: reference at (size_type po
    1 min read
  • std::basic_string::operator[] in C++
    Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined. Syntax : reference operator[] (size_type pos); const_reference operator[] (size_type pos) const; Parameters : pos - position of the character to return Retu
    1 min read
  • std::string::size() in C++
    The std::string::size() function in C++ is a built-in method of the std::string class that is used to determine the number of characters in the string. All characters up to the null character are considered while calculating the size of the string. In this article, we will learn about string::size()
    2 min read
  • std::basic_string::max_size in C++
    std::basic_string::max_size is used to compute the maximum number of elements the string is able to hold due to system or library implementation limitations. size_type max_size() const; Parameters : None Return value : Maximum number of characters Exceptions : None // CPP program to compute the limi
    1 min read
  • std::string class in C++
    C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. String vs Character ArrayString Ch
    8 min read
  • std::string::clear in C++
    The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters. Parameters: none Return Value: none void string ::clear () - Removes all characters (makes string empty) - Doesn't throw any error - Receives no parameters and returns nothing // CPP
    1 min read
  • std::string::assign() in C++
    The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. string& string::assign (const string& str) str : is the string to be assigned. Returns : *this C/C++ Code // CPP code for
    5 min read
  • std::string::append() in C++
    The string::append() in C++ is used append the characters or the string at the end of the string. It is the member function of std::string class . The string::append() function can be used to do the following append operations: Table of Content Append a Whole StringAppend a Part of the StringAppend
    3 min read
  • std::string::insert() in C++
    In C++, the string::insert() function is used insert the characters or a string at the given position of the string. It is the member function of std::string class. The string::insert method can be used in the following ways to: Table of Content Insert a Single CharacterInsert a Single Character Mul
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences