Skip to content

Commit ae04f6f

Browse files
[Entry] C++ Strings: erase() (#7351)
* [Entry] C++ Strings: erase() * minor fix * Update erase.md * format fix ---------
1 parent f8d0ac6 commit ae04f6f

File tree

1 file changed

+168
-0
lines changed
  • content/cpp/concepts/strings/terms/erase

1 file changed

+168
-0
lines changed
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
---
2+
Title: '.erase()'
3+
Description: 'Removes characters from a C++ string object.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Web Development'
7+
Tags:
8+
- 'Functions'
9+
- 'Methods'
10+
- 'Memory'
11+
- 'Strings'
12+
CatalogContent:
13+
- 'learn-c-plus-plus'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`.erase()`** method is a built-in member function of the C++ `string` class that removes characters from a string object. It provides several overloaded versions to delete specific characters, ranges of characters, or clear the entire string, effectively shortening the string's length and modifying the original string in place.
18+
19+
## Syntax
20+
21+
The `.erase()` method has three main overloads:
22+
23+
```pseudo
24+
string.erase()
25+
string.erase(pos, len)
26+
string.erase(iterator)
27+
string.erase(first, last)
28+
```
29+
30+
**Parameters:**
31+
32+
- `pos`: Position (index) of the first character to be erased (0-based indexing)
33+
- `len`: Number of characters to erase from the starting position
34+
- `iterator`: Iterator pointing to the character to be removed
35+
- `first`: Iterator pointing to the first character in the range to be erased
36+
- `last`: Iterator pointing to one position past the last character in the range
37+
38+
**Return value:**
39+
40+
Returns an iterator pointing to the character that now occupies the position of the first erased character. If no characters remain after the erased portion, returns `string::end()`.
41+
42+
## Example 1: Character Removal Using `.erase()`
43+
44+
This example demonstrates removing a single character from a specific position in a string:
45+
46+
```cpp
47+
#include <iostream>
48+
#include <string>
49+
50+
using namespace std;
51+
52+
int main() {
53+
string text = "Hello World!";
54+
55+
// Remove the character at index 5 (space character)
56+
text.erase(5, 1);
57+
58+
cout << text << endl;
59+
60+
return 0;
61+
}
62+
```
63+
64+
The output of this code is:
65+
66+
```shell
67+
HelloWorld!
68+
```
69+
70+
The code removes one character starting at position 5, which eliminates the space between "Hello" and "World".
71+
72+
## Example 2: Text Processing Application Using `.erase()`
73+
74+
This example shows how `.erase()` can be used in a real-world text processing scenario to remove unwanted characters from user input:
75+
76+
```cpp
77+
#include <iostream>
78+
#include <string>
79+
80+
using namespace std;
81+
82+
int main() {
83+
string userInput = "[email protected]###";
84+
85+
// Find and remove trailing special characters
86+
size_t hashPos = userInput.find('#');
87+
if (hashPos != string::npos) {
88+
// Erase everything from the first '#' to the end
89+
userInput.erase(hashPos);
90+
}
91+
92+
cout << "Cleaned email: " << userInput << endl;
93+
94+
return 0;
95+
}
96+
```
97+
98+
The output of this code is:
99+
100+
```shell
101+
Cleaned email: [email protected]
102+
```
103+
104+
This example demonstrates cleaning user input by removing unwanted trailing characters, which is common in data validation and preprocessing applications.
105+
106+
## Codebyte Example: String Formatting Tool
107+
108+
This example shows using `.erase()` with iterators to remove specific words from a sentence, useful for content filtering or text formatting applications:
109+
110+
```codebyte/cpp
111+
#include <iostream>
112+
#include <string>
113+
114+
using namespace std;
115+
116+
int main() {
117+
string sentence = "This is a very long sentence";
118+
119+
// Find the word "very " and remove it
120+
size_t pos = sentence.find("very ");
121+
if (pos != string::npos) {
122+
// Remove "very " (5 characters including space)
123+
sentence.erase(pos, 5);
124+
}
125+
126+
cout << "Modified sentence: " << sentence << endl;
127+
128+
// Clear the entire string using erase()
129+
sentence.erase();
130+
cout << "String length after clearing: " << sentence.length() << endl;
131+
132+
return 0;
133+
}
134+
```
135+
136+
This example shows both selective word removal and complete string clearing, demonstrating the versatility of `.erase()` in text manipulation applications.
137+
138+
## Frequently Asked Questions
139+
140+
### 1. How do I clear a string in C++?
141+
142+
Use the `.erase()` method without any parameters to clear the entire string:
143+
144+
```cpp
145+
string text = "Hello World";
146+
text.erase(); // Clears the entire string
147+
```
148+
149+
Alternatively, you can use `.clear()` method which is more explicit for this purpose.
150+
151+
### 2. How to erase space in string in C++?
152+
153+
To remove all spaces from a string, you can use `.erase()` in combination with algorithms:
154+
155+
```cpp
156+
#include <algorithm>
157+
#include <string>
158+
159+
using namespace std;
160+
161+
string text = "Hello World Example";
162+
text.erase(remove(text.begin(), text.end(), ' '), text.end());
163+
// Result: "HelloWorldExample"
164+
```
165+
166+
### 3. What happens if I use an invalid index with `.erase()`?
167+
168+
If you provide an index that exceeds the string length, `.erase()` throws a `out_of_range` exception. Always ensure the position is within valid bounds (0 to `string.length()-1`) before calling `.erase()`.

0 commit comments

Comments
 (0)