Replace Words
Problem
Given a string. Replace the words whose length>=4 and is even, with a space between the two equal halves of the word. Consideronly alphabets for finding the evenness of the word
I/P "A person can't walk in this street"
O/P "A per son ca n't wa lk in th is str eet"
Solution
1 public static String replaceWords(String s) { 2 StringBuilder sb = new StringBuilder(); 3 if (s == null) 4 return sb.toString(); 5 6 char[] arr = s.toCharArray(); 7 int n = 0; 8 int length = 0; 9 while (n < arr.length) { 10 if (arr[n] == ' ') { 11 if (length >= 4 && (length-1)%2 == 0) { 12 sb.append(s.substring(n - length, n - length / 2)); 13 sb.append(' '); 14 sb.append(s.substring(n - length / 2, n)); 15 length = 0; 16 } 17 else { 18 sb.append(s.substring(n - length, n)); 19 length = 0; 20 } 21 } 22 length++; 23 n++; 24 } 25 return sb.toString(); 26 }