Abo Hani Abo Hani - 1 year ago 73
Java Question

Can't replace specific letters with another one correctly

I have a String, and i'd like to repalce specific letters with another one, I have a json response that contain which letter to replaced with which letter .

For example, my String is 'abh f'
And Json from and to will be - a => bf , b => 423_ , h => 2Re , f => ab

Here's the issue, when replaceing, it will first replace a to bf, and then it will replace the b in abh and the b in converted a (bf), and that will corrupt the whole idea, i couldn't come with a good idea, i've tried looping throw each letter from the string but i wasn't able to loop throw the json without getting OutOfMemory .

Any Ideas? here's the code

for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);

String Original = jo_inside.getString("from");
String To = jo_inside.getString("to");

NewText = NewText.replace(" ","$");
NewText = NewText.replace(Original ,To);

Answer Source

You could first replace each input string with a token, like {i} where i is the index of the input, and afterwards replace every token with the output string of the corresponding index.

You just have to make sure that the token is not contained in the original string nor the inputs/outputs.

That's, however, easier but very inefficient. The best way would be to iterate over the string with a for per char, and perform the replace by hand, that is, something like this:

String input = /* param of your method */;

Map<Character, String> replacements = new HashMap<>();
// Fill map in, like replacements.put('a', "bf");
// Parsing the json every time could be time consuming.
// The best structure here is a HashMap.
// So I'd suggest that you first create it from the json and then use it whenever.

String output = "";

for (char c : input.toCharArray()) {
    if (map.containsKey(c)) {
        output += map.get(c);
    } else {
        output += c;

return output; // the result is here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download