how do i remove a reoccurrence of a value in a string:
this is how i started it
string message = " classic class"
char r = 's"
i now want to remove all the char remove in string message using a void function
void remove(string message, char r)
string::size_type pos, stop;
pos = message.find(r, 0);
stop = message.length();
while (pos %26lt; stop){
message.erase (pos,stop);
pos = message.find (c, pos + 1);
}
cout %26lt;%26lt; message%26lt;%26lt; endl;
somehow i cannot get an output, displaying .......claic cla
can someone please help me
Remove values in a string in c++ programming?
i think that the mistake was in this line
message.erase(pos,stop) in the while loop
coz when you did this pos=message.find(r,0);
pos locates the first 's' in the string
and stop=message.length;
so when u wrote this //message.erase(pos,stop);
it removes all the characters starting from the first 's'
u located with (pos) to the end of the string (stop)
and the string then becomes "cla"
u can do this
string message="classic class";
char r='s';
while (message.find(r)!=string::npos) /*message.find(r) returns string::npos if it doesn't find the char 's' and when this happens it breaks the loop */
{
string::size_type pos=message.find(r);
message.erase(pos,1); /* 1 in the second parameter to erase only one character which must be an 's' */
}
cout%26lt;%26lt;message%26lt;%26lt;endl;
/* pure code to use :D */
string message="classic class";
char r='s';
while (message.find(r)!=string::npos)
{
string::size_type pos=message.find(r);
message.erase(pos,1);
}
cout%26lt;%26lt;message%26lt;%26lt;endl;
hope i helped u and sorry for my bad english :$
Reply:I haven't done C++ in a while, but I did notice a few things:
1. "message.erase (pos,stop);"
Seems like you're removing everything from the first "s" to the length of the message.
2. "pos = message.find (c, pos + 1);"
'c' is not declared? This doesn't seem good if the letter is removed, since all the letters are renumbered. That is assuming the erase function does what you say.
3. "while (pos %26lt; stop){"
Perhaps you should test the condition if nothing is found in the 'pos' variable?
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment