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:
String find() in C++
Next article icon

string erase in C++

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The string erase() function is a built-in function of the string class that is used to erase the whole or part of the string, shortening its length. The function provides different ways to delete a portion of a string based on either an index position or a range of characters or delete the whole string.

Example :

C++
//Driver Code Starts{ #include <iostream> #include <string> using namespace std;  int main() { //Driver Code Ends }      string str = "Hello, World!";      // Erase a single character sterting     // from index 5     str.erase(5, 1);  //Driver Code Starts{          cout << str;     return 0; } //Driver Code Ends } 

Output
Hello World!

Syntax

The string erase() function provides 5 different overloads for different purposes:

C++
s.erase()                   // Erases whole string s.erase(idx)             // Erases all characters after idx s.erase(idx, k)        // Erases k characters after idx s.erase(itr)             // Erases character at itr s.erase(first, last) // Erases character in range [first, last) 

Let’s look at how to use each overload one by one.

Table of Content

  • Erase Single Character from Given Position
  • Erase Range of Characters
  • Erase k Characters After Given Position
  • Erase All Characters After Given Position
  • Erase All Characters

Erase Single Character from Given Position

string erase() function can be used for erasing a single character from the specific position in the string.

Syntax

C++
s.erase(itr) 

Parameters

  • itr: Iterator to the character you want to erase (note that it is an iterator, not index)

Return Value

  • Returns the character now at the position of the removed character.
  • If no such character is remaining, returns iterator to the string::end()

Example

C++
#include <iostream> #include <string> using namespace std;  int main() {     string s("Hello World!");      // Deletes character at position 4     s.erase(s.begin() + 4);      cout << s;     return 0; } 

Output
Hell World!

Erase Range of Characters

We can also erase a range of characters from the string using string erase() function.

Syntax

C++
s.erase(first, last) 

Parameters

  • first: Iterator to the first element in the range.
  • last: Iterator to one element after the last element in the range.

Return Value

  • Returns the character now at the position of the first removed character.
  • If no such character is remaining, returns iterator to the string::end()

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s("Hello World!");      // Define the range as the word "Hello "   	auto first = s.begin();   	auto last = s.begin() + 6;   	   	// Remove the range [first, last)     s.erase(first, last);        cout << s;     return 0; } 

Output
World!

Erase k Characters After Given Position

The below version erases all the characters after the given index, but we can also limit the number of characters to be deleted using string::erase.

Syntax

C++
s.erase(idx, k) 

Parameters

  • idx: The position (index) at which character deletion begins.
  • k: Number of characters to be erased (including character at idx).

Return Value

  • This version returns the current string.

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s("Hello World!");      // Deletes 5 characters starting from index number 0     s.erase(0, 5);      cout << s;     return 0; } 

Output
 World!

Erase All Characters After Given Position

string erase() function can also be instructed to erase the characters after some given position.

Syntax

C++
s.erase(idx) 

Parameters

  • idx: The position (index) at which character deletion begins.

Return Value

  • This version returns the current string.

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s("Hello World!");    	// Deletes the word " World!"     s.erase(5);        cout << s;     return 0; } 

Output
Hello

Erase All Characters

The string erase() function is able to delete all the characters of the string effectively clearing it. The length of the string will be reduced to 0.

Syntax

C++
s.erase() 

Parameter

  • This version takes no parameters.

Return Value

  • This version returns the current string.

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s("Hello World!");      // Erasing string using string::erase()     s.erase();      cout << s;     return 0; } 


Output

(no output)

string erase() vs string clear()

The string clear() is a function used to erase the contents of the string, but it is a lot different from string erase(). Below is the table that lists the major differences between string erase() and string clear().

Aspectstring::erase()string::clear()
PurposeRemoves specific characters or a range of characters.Removes all characters from the string.
Syntaxerase(position);
erase(first, last);
clear();
Parameters– Position of a single character
– Range of characters (two iterators)
None
ReturnsIterator pointing to the position after the removed rangeNone
Time Complexity– Single character: O(m), where m is the number of characters after the position.
– Range: O(m – k), where k is the size of the range.
O(1), where n is the number of characters in the string.
Space ComplexityO(1), as it modifies the string in place.O(1), as it clears the string in place.


Next Article
String find() in C++

S

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

Similar Reads

  • getline (string) in C++
    The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It extracts the characters from the input stream and appends it to the given string object until the delimiting character is encountered. Example: [GFGTABS] C++ //Driver Code Starts{ #inclu
    3 min read
  • Strings in C++
    In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class. Creating a StringCreating a st
    6 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
  • String find() in C++
    In C++, string find() is a built-in library function used to find the first occurrence of a substring in the given string. Let’s take a look at a simple example that shows the how to use this function: [GFGTABS] C++ #include <bits/stdc++.h> using namespace std; int main() { string s = "We
    4 min read
  • string at() in C++
    The std::string::at() in C++ is a built-in function of std::string class that is used to extract the character from the given index of string. In this article, we will learn how to use string::at() in C++. Syntaxstr.at(idx) Parametersidx: Index at which we have to find the character.Return ValueRetu
    1 min read
  • std::string::compare() in C++
    The string::compare() function in C++ is used to compare a string or the part of string with another string or substring. It is the member function of std::string class defined inside <string> header file. In this article, we will learn how to use string::compare() in C++. The different ways t
    4 min read
  • std::string::data() in C++
    The data() function writes the characters of the string into an array. It returns a pointer to the array, obtained from conversion of string to the array. Its Return type is not a valid C-string as no '\0' character gets appended at the end of array. Syntax: const char* data() const; char* is the po
    2 min read
  • Arrays and Strings in C++
    Arrays An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection
    5 min read
  • String Functions in C++
    A string is referred to as an array of characters. In C++, a stream/sequence of characters is stored in a char array. C++ includes the std::string class that is used to represent strings. It is one of the most fundamental datatypes in C++ and it comes with a huge set of inbuilt functions. In this ar
    9 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