0

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...

5
Contributors
4
Replies
7
Views
4 Years
Discussion Span
Last Post by vijayan121
0

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.

0

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.

Edited by np complete

0

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.

1

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/

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.