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: [email protected],userd%40gmail.com,[email protected]

3
  • Do you mean that it only replaces the first instance of "%40" with '@' and you would like it to replace all instances of "%40"? Commented Oct 11, 2015 at 5:42
  • I mean that yes, replace all% 40 to @ Commented Oct 11, 2015 at 5:43
  • Why is the string data = text initialization needed instead of string data = "..."? Commented Oct 11, 2015 at 5:44

2 Answers 2

1

You can put it into a loop:

char text[4080] = "asdnisadnias%40gmail.com,userd%40gmail.com,[email protected]"; 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

char text[4080] = "asdnisadnias%40gmail.com,userd%40gmail.com,[email protected]"; string data = text; size_t post; while((post = data.find("%40")) != string::npos) { data.replace(post,3,"@"); } cout<<data; 

7 Comments

you are using size_t for signed values of type bool, you need to cast expression to (size_t)
like this : while((post = (size_t) (data.find("%40") != string::npos)))
I don't think so. It compares size_t (find) to size_t (string::npos) which results in bool. It compiles without warning.
It will compile but it is a good practice to cast it for understanding :)
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
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.