Abo Hani Abo Hani - 1 month ago 6
Java Question

Replacing letters in two strings

I have two Strings and a Json response :


  1. InputString = "ab";

  2. OutputString = "";

  3. Json(example, not real one): Array(From:a,to:bhduh - From:b, to:eiaja).



*Json isn't a real response, it has 2 records for this example .

What i want to do is to replace
a
with
bhduh
and
b
with
eiaja
, I have a JSON loop which tell me to what i should replace, and i need to do it inside that loop, So here's what i tried :

InputString = InputString.replace(From,To);


Output

eiajahduheiaja


Expected Output

bhduheiaja


This's happening because in the first loop, it's changing
a
, and in the second loop, there's two
b
, the
b
in
bhduh
and
b
in the normal String.

The loop times depend on letters count, so sometimes it can be 5 or 6, depending on the server Json response.

What i want is to have the Expected Output, any ideas ?

Answer

It is unclear what JSON you have, but I'm guessing your problem is that you are replacing a with bhduh, (which contains a b), then you try to replace b with some other stuff. Obviously that isn't correct.

You need to loop over your initial input, then append your replacements to some other string, not replace upon your input.

For example, using a HashMap

public static void main (String[] args) throws java.lang.Exception
{
    String input = "ab";
    HashMap<Character, String> replacements = new HashMap<Character, String>() {{
        put('a', "bhduh");
        put('b', "eiaja");
    }};

    StringBuilder sb = new StringBuilder();
    for (char c : input.toCharArray()) {
        String rep = replacements.get(c);
        if (rep != null) {
            sb.append(rep);
        }
    }
    System.out.println(sb.toString());
}

Example