c++ string remove code example
Example 1: remove or erase first and last character of string c++
str.pop_back();
str.erase(str.begin());
Example 2: removing a character from a string in c++
#include<iostream>
#include<algorithm>
using namespace std;
main() {
string my_str = "ABAABACCABA";
cout << "Initial string: " << my_str << endl;
my_str.erase(remove(my_str.begin(), my_str.end(), 'A'), my_str.end());
cout << "Final string: " << my_str;
}
Example 3: c++ remove space from string
static std::string removeSpaces(std::string str)
{
str.erase(remove(str.begin(), str.end(), ' '), str.end());
return str;
}
Example 4: erasing a character from a string in c++
#include <iostream>
#include <string>
int main ()
{
std::string str ("This is an example sentence.");
std::cout << str << '\n';
str.erase (10,8);
std::cout << str << '\n';
str.erase (str.begin()+9);
std::cout << str << '\n';
str.erase (str.begin()+5, str.end()-9);
std::cout << str << '\n';
return 0;
}
Example 5: string erase character c++
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string s = "This is an example";
std::cout << s << '\n';
s.erase(0, 5);
std::cout << s << '\n';
s.erase(std::find(s.begin(), s.end(), ' '));
std::cout << s << '\n';
s.erase(s.find(' '));
std::cout << s << '\n';
}
Example 6: erase string c++
string& erase (size_t pos = 0, size_t len = npos);