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

123\n~~~\n789\n~~~\n

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

456\n~~~\n789\n~~~\n


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.

erase()
http://www.cplusplus.com/reference/string/string/erase.html

find()
http://www.cplusplus.com/reference/string/string/find.html

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?

edit:
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

myNumbers
3/2
3/2
3/2

~~


/3
~~

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

1
2
3
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:
1
2
3
4
5
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
Hi,
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("~~"));

____________________
Regards,
Rammohan Alampally,
rammohan@india.com
Technical Lead,
Bangalore, India.
www.FindSyntax.com -> Worlds first Web based Windows O/S is a Brain Chaild of Rammohan
Topic archived. No new replies allowed.