Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can anyone tell me how to replace multiple characters at a time in a string

Eg: codeproject@discussion.com

How to replace all 'o's with 'e's and all 'e's with 'o's.

Is it possible using replaceAll() function of String class ? or for loop is needed?

What I have tried:

I have tried using replaceAll() function , but I can replace only one character at a time
Posted
Updated 13-Dec-19 23:24pm

Write a method to iterate the characters and do it.

Also, have a look at the entries for this:
https://www.codeproject.com/Questions/1157796/Coding-challenge-bad-word-filter
 
Share this answer
 
v2
The problem with replaceAll is that once you will have replaced all o's with e's, you will not be able to differentiate original e's from replaced ones.
So you have to resort to a good old iteration on characters.
One of possible ways would be to maintain a dictionary of characters to be replaced, the key being the character to replace, and the value would be the replacement char. Upon iteration over original string, if current character is in the dictionary, replace it, otherwise leave it unchanged.
As this has a strong smell of homework, I won't provde any actual code; but would be glad to help further if you can come up at least with some basic implementation.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900