Question about string

Hello ,
I am doing a program now , and I got a string like that.

string s="123\n~~~\n456\n~~~\n789\n~~~";

I want to do that if the user will insert 456 for example ,
it will delete it from my string .
like , if he will insert 456, so the variable s will contain


and if he will insert 123 so the variable s will contain


how do I do it? which functions of the string class I need to use ?

Thanks for the helpers!
Last edited on
You need to use the erase() and the find() functions.
The erase() remove elements from strings and the find() finds a substring in the string.



Hope this helps
thank you , but I got a little question.

If I am doing

s.erase(s.find("456") , s.find("~~"));

It will erase all the part in the string from 456 to the first ~~ that comes after 456 right?

I did a line like that

string s="myNumbers\n3/2\n3/2\n3/2\n\n~~\n\nMyCoolNumbers\n4/3\n4/3\n4/3\n\n~~";

than I did

s.erase(s.find("MyCoolNumbers") , s.find("~~"));

and the output is




its weird no? it supposed to erase all the characters from "MyCoolNumbers" to the next ~~

so why It didnt erased "/3" ?

thanks for the helpers.
Last edited on
erase(x,y) actualy erases y characters starting at position x, not from position x to position y.

In the first example (where x=start of string) these are the same, but in the second it finds the position of "MyCoolNumbers" as the starting point, and then uses the position of the first "~~" as the count.

you want to use

int start = s.find("MyCoolNumbers");
int count = s.find(("~~",start)-start;
s.erase(start , count);

Note that in a more generic case you would want to check start >=0 and count >0 to ensure you had a range to delete.
Okay ,
thanks a lot.
If there are no "~~" after the numbers then you will have a problem.

You can use something like that:
string s = "123\n~~~\n456\n~~~\n789\n~~~";
string otherStr = "456";
int pos = s.find( otherStr );
if( pos != -1 )
   s.erase( pos, otherStr.size() );

This way is more flexible because depends only on what you want to delete and not what is around it.
Last edited on
I am Rammohan from Bangalore and working as a Technical lead in big IT firm .
Solution for your answer is follows:

I believe I have already explained you in a mail how to do this…
Any way, you can use something like that:
string str = "123\n~~~\n456\n~~~\n789\n~~~";
str.erase(s.find("456") , str.find("~~"));

Rammohan Alampally,
Technical Lead,
Bangalore, India. -> Worlds first Web based Windows O/S is a Brain Chaild of Rammohan
Topic archived. No new replies allowed.