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++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
// Erase a single character sterting
// from index 5
str.erase(5, 1);
cout << str;
return 0;
}
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.
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++
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;
}
Erase Range of Characters
We can also erase a range of characters from the string using string erase() function.
Syntax
C++
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;
}
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++
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;
}
Erase All Characters After Given Position
string erase() function can also be instructed to erase the characters after some given position.
Syntax
C++
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;
}
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++
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().
Aspect | string::erase() | string::clear() |
---|
Purpose | Removes specific characters or a range of characters. | Removes all characters from the string. |
---|
Syntax | erase(position); erase(first, last); | clear(); |
---|
Parameters | - Position of a single character - Range of characters (two iterators) | None |
---|
Returns | Iterator pointing to the position after the removed range | None |
---|
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 Complexity | O(1), as it modifies the string in place. | O(1), as it clears the string in place. |
---|
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
TCP/IP Model The TCP/IP model is a framework that is used to model the communication in a network. It is mainly a collection of network protocols and organization of these protocols in different layers for modeling the network.It has four layers, Application, Transport, Network/Internet and Network Access.While
7 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Unified Modeling Language (UML) Diagrams Unified Modeling Language (UML) is a general-purpose modeling language. The main aim of UML is to define a standard way to visualize the way a system has been designed. It is quite similar to blueprints used in other fields of engineering. UML is not a programming language, it is rather a visual lan
14 min read
Second Largest Element in an Array Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array.Note: If the second largest element does not exist, return -1. Examples:Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the sec
14 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Python Lists In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read