I'm a beginner so bear with me.

I have a string and in it there is a character I want to remove.

What is the best way to remove it?

The shit I've found on the internet, it's making my head explode.

I found this:

str.erase(std::remove(str.begin(), str.end()), str.end());

Why is there a std::remove in the str.erase()? What does str.begin(), str.end() do if they're in std::remove?

string::iterator it;
it=str.begin()+9;
str.erase(it);
cout << str << endl;  

The line here I don't get is "string:;iterator it;" Because there's something magical happening there. I tried making a variable "it=9", it didn't work.

I'm going to sleep...

Recommended Answers

I have a string and in it there is a character I want to remove.
What is the best way to remove it?

Remove char at position pos in string str
str.erase( pos, 1 ) ;
or str.erase( str.begin() + pos ) ;
or str = …

Jump to Post

All 4 Replies

Did you actually look up the erase and remove methods of the string class? I'll bet their description would help you determine how and why and which to use.

I would recommend that you first do this problem without using these functions. Do it by simple string array manipulation.

You may consult this for reference to above mentioned functions.

Sort-of Pseudo-Code:
1. Find position of character in string.
2. Copy from position+1 to end of string to position (ie, move up remainder 1 character).
3. Terminate string (if necessary).
4. Done.

I have a string and in it there is a character I want to remove.
What is the best way to remove it?

Remove char at position pos in string str
str.erase( pos, 1 ) ;
or str.erase( str.begin() + pos ) ;
or str = str.substr(0,pos) + str.substr(pos) ;

Remove the first occurrance of char ch in string str

    auto pos = str.find( ch ) ;
    if( pos != std::string::npos ) str.erase( pos, 1 ) ;

Remove all occurrances of char ch in string str
str.erase( std::remove( str.begin(), str.end(), c ), str.end() ) ;

The line here I don't get is "string:;iterator it;" Because there's something magical happening there. I tried making a variable "it=9", it didn't work.

Apparently you have not been exposed to iterators and algorithms. Essential knowlegde for someone starting out to explore C++.

Perhaps this tutorial would be a good starting point: http://www.mochima.com/tutorials/STL.html

Then lookup the algorithm std::remove() http://www.cplusplus.com/reference/algorithm/remove/
and the string member function std::string::erase() http://www.cplusplus.com/reference/string/string/erase/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.