1str.pop_back(); // removes last /back character from str
2str.erase(str.begin()); // removes first/front character from str
1// string::erase
2#include <iostream>
3#include <string>
4
5int main ()
6{
7 std::string str ("This is an example sentence.");
8 std::cout << str << '\n';
9 // "This is an example sentence."
10 str.erase (10,8); // ^^^^^^^^
11 std::cout << str << '\n';
12 // "This is an sentence."
13 str.erase (str.begin()+9); // ^
14 std::cout << str << '\n';
15 // "This is a sentence."
16 str.erase (str.begin()+5, str.end()-9); // ^^^^^
17 std::cout << str << '\n';
18 // "This sentence."
19 return 0;
20}
1#include <iostream>
2#include <algorithm>
3#include <string>
4
5int main()
6{
7 std::string s = "This is an example";
8 std::cout << s << '\n';
9
10 s.erase(0, 5); // Erase "This "
11 std::cout << s << '\n';
12
13 s.erase(std::find(s.begin(), s.end(), ' ')); // Erase ' '
14 std::cout << s << '\n';
15
16 s.erase(s.find(' ')); // Trim from ' ' to the end of the string
17 std::cout << s << '\n';
18}
1#include<iostream>
2#include<string>
3
4using namespace std;
5int main()
6{
7 string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
8
9 cout << "Initial string: " << text << endl;
10
11 text.erase(10, string::npos);
12 // string.erase(pos1, pos2) removes the part of the string between position 1 and 2.
13 // In this case, between character 10 and the end of the string.
14
15 cout << "Final string: " << text;
16}
1 string& erase (size_t pos = 0, size_t len = npos);
2/*
3pos
4Position of the first character to be erased.
5If this is greater than the string length, it throws out_of_range.
6Note: The first character in str is denoted by a value of 0 (not 1).
7len
8Number of characters to erase (if the string is shorter, as many characters as possible are erased).
9A value of string::npos indicates all characters until the end of the string.
10*/