0

I found a little mistake, when I enter my email, find results that do not match expectations and the result is a symbol '@' turned into '%40', I would like to change the text '%40' became a symbol of a '@'. ok simple question, if found ' %40' row character strings automatically becomes the symbol of ' @'.

the code below can only work 1 time, but I would like to find any text '%40' in his Fox be @

char text[4080] = "asdnisadnias%40gmail.com,userd%40gmail.com,aas%40mail.com";
string data = text;
size_t post;
post = data.find("%40");
data.replace(post,3,"@");
cout<<data;

out: asdnisadnias@gmail.com,userd%40gmail.com,aas@mail.com

kramster
  • 25
  • 9

2 Answers2

1

You can put it into a loop:

char text[4080] = "asdnisadnias%40gmail.com,userd%40gmail.com,aas@mail.com";
string data = text;
for (size_t pos = 0; (pos = data.find("%40", pos)) != std::string::npos; pos++)
{
    data.replace(pos,3,"@");
}
cout << data;

Here, pos keeps track of the position you have searched up to, starting at index 0 (start of the string). Then, you keep calling find on the data with that position, until you get std::string::npos indicating no more matches.

In this case, pos++ is not strictly required, but we can increment by 1, because we replace with "@" which has length 1. This might be important in cases like replacing double backslashes with a single backslash.

ronalchn
  • 12,225
  • 10
  • 51
  • 61
1

Simple keep replacing while there is some concurrence. For email it is effective enough.

char text[4080] = "asdnisadnias%40gmail.com,userd%40gmail.com,aas@mail.com";
string data = text;
size_t post;
while((post = data.find("%40")) != string::npos)
{
    data.replace(post,3,"@");
}
cout<<data;
Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
  • you are using size_t for signed values of type bool, you need to cast expression to (size_t) – vishal Oct 11 '15 at 05:47
  • like this : while((post = (size_t) (data.find("%40") != string::npos))) – vishal Oct 11 '15 at 05:47
  • I don't think so. It compares size_t (find) to size_t (string::npos) which results in bool. It compiles without warning. – Tomas Kubes Oct 11 '15 at 05:51
  • It will compile but it is a good practice to cast it for understanding :) – vishal Oct 11 '15 at 05:52
  • There is NO casting. All types are the same. Do you cast following code with int: while(n != 0){..} No, because you are comparing two number of same type. Check documentation of string::find and string::npos – Tomas Kubes Oct 11 '15 at 05:56
  • @vishal, what you pointed out is a bug in his code, just not quite what you thought. Because of operator precedence, the `!=` is executed first, and you get a boolean result. He then tries to assign the boolean to `post`, which is `size_t`. Therefore, his code is incorrect. – ronalchn Oct 11 '15 at 06:06
  • You are right, I changed while((post = data.find("%40") != string::npos)) to while((post = data.find("%40")) != string::npos) – Tomas Kubes Oct 11 '15 at 07:21