Problem
From a given string, replace all instances of 'a' with 'one' and 'A' with 'ONE'.
Example Input: " A boy is playing in a garden"
Example Output: " ONE boy is playing in onegarden"
-- Not that 'A' and 'a' are to be replaced only when theyare single characters, not as part of another word.
Solution
1 public static String replaceString(String s) { 2 // s = s.replace("a ", "one "); 3 // s = s.replace("A ", "ONE "); 4 5 // s = s.replaceAll("\b(a)", "one"); 6 // s = s.replaceAll("\b(A)", "ONE"); 7 8 StringBuilder sb = new StringBuilder(); 9 for(String str : s.split(" ")) { 10 if(str.equals("a")) sb.append("one "); 11 else if(str.equals("A")) sb.append("ONE "); 12 else sb.append(str + " "); 13 } 14 15 return sb.toString(); 16 }