Swap positions of the first appearance of letter ‘a’ with the last appearance of letter ‘o’ Java

The task is asking me to make from the String, for example “aaligatoor”, output like: “oaligatoar” I found a solution like:

public static String letterReplacement(final String word) {
            String o = "o";
            String a = "a";
            if (word.contains("a") && word.contains("o")) {
                return word.replaceFirst("a", "o")
                           .replaceFirst("(?s)(.*)" + 'o', "$1" + 'a');
            } else {
                return "Your word does not contain both of 'a' and 'o' letters, sorry...";
            }
        }

but it looks tricky, maybe someone knows any more understandable ways to solve this? I appreciate your assistance and attention very much.

Answer

Find the first index of the “a” (String.indexOf()) and the last index of “o” (String.lastIndexOf()). If both indexes are > -1 then swap the letters

Something like:

public class StackOverflow {
    public static void main(String[] args) {
        String data = "aaligatoor";

        int firstAindex = data.indexOf("a");
        int lastOindex = data.lastIndexOf("o");

        if (firstAindex > -1 && lastOindex > -1) {
            char[] letters = data.toCharArray();
            letters[firstAindex] = 'o';
            letters[lastOindex] = 'a';

            data = new String(letters);
        }
        System.out.println(data);
    }
}

Result

oaligatoar

Leave a Reply

Your email address will not be published. Required fields are marked *