Writing a program which exchanges the letters "e" and "o" in one string using the `replace` method

Viewed 719

For example, if I have Hello World it should become Holle Werld. How can I do this using String.replace? I've tried doing "Hello World".replace("e","o") but I only get Hollo World and if I use it again I will get Helle Werld.

6 Answers

You could also do:

String result = Arrays.stream(input.split(""))
                      .map(c -> c.equals("e") ? "o" : c.equals("o") ? "e" : c)
                      .collect(Collectors.joining());

Optimized Java 8 solution:

String str = "Hello World!";

String result = str.codePoints()
                   .map(c -> c == 'e' ? 'o' : c == 'o' ? 'e' : c)
                   .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                   .toString();

This solution avoids using highweight methods like String.replace, String.split and even String.equals.

I might treat the string as a character array here, and iterate over it:

String input = "Hello World";
char[] letters = input.toCharArray();
for (int i=0; i < letters.length; ++i) {
    if (letters[i] == 'e') {
        letters[i] = 'o';
    }
    else if (letters[i] == 'o') {
        letters[i] = 'e';
    }
}

String output = new String(letters);
System.out.println(input);
System.out.println(output);

Hello World
Holle Werld

Note that we could try doing a String#replace here, using a dummy character as a placeholder. But that runs the risk of the placeholder appearing somewhere as part of the string. The above solution would work in all cases.

Following a suggestion by @Carlos Heuberger, you can use '\uFFFF' as a placeholder to interchange the characters with each other using the String.replace() method.. '\uFFFF' is considered a non-character in Unicode (i.e., it cannot appear in a String).

 String str = "Hello World";
 str = str.replace('o', '\uFFFF').replace('e', 'o').replace('\uFFFF', 'e');

Hope it helps.

I'm assuming you have to use replace()
Following is one way to do it:

String input = "Hello World";
input = input.replace("e","~");
input = input.replace("o","e");
input =input.replace("~","o);

Note: This assumes String won't have "~" in it. This code isn't robust enough code to handle that scenario.

You can also find a character or a combination of characters that are not contained in your string, and use it as a temporary string of replacement. Here is an example :

private void funnyReplace2(String myString){
    String unused = findUnused(myString);
    System.out.println("Unused character(s) used : "+unused);
    myString=myString.replace("e",unused);
    myString=myString.replace("o","e");
    myString=myString.replace(unused,"o");

    System.out.println(myString);

}

private String findUnused(String aString){
    String lookingForChar = "@#{}]@$^£¨*ù%µ§/.?,;:!&é()-èïô";
    int looper = 0;
    while(looper<lookingForChar.length()){
        looper++;
        for (int i =0; i<=lookingForChar.length()-looper; i++){
            if (!aString.contains(lookingForChar.substring(i,i+looper)))
                return lookingForChar.substring(i,i+looper);
        }
    }
    return "What kind of String do you have ??";
}
Related