Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Swap positions of the first appearance of letter ‘a’ with the last appearance of letter ‘o’ Java without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
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
We are here to answer your question about Swap positions of the first appearance of letter ‘a’ with the last appearance of letter ‘o’ Java - If you find the proper solution, please don't forgot to share this with your team members.