Format a string: remove redundant space characters
Today, I came across one interesting question about string format:
“Format a string so that each word is separated each other by exactly one space. Also there is no preceding and trailing spaces before the first and last word. Try to optimize it without using additional arrays, just some temporary variables.
For exampe:
“____________” -> “”
“ABCD” -> “ABCD”
“AB__CD” -> “AB_CD”
“______A__B______C_D______” -> “A_B_C_D”
My idea is using two indexes iterating through each character in a String. One index is just used to iterate each character. One index is keep track the length of format string.
Here is the sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //input: a String, convert it to array. //output: return formated String public String removeBlanks(String str){ int strLength = str.length(); char[] seq = new char[strLength+1]; int length = -1; for (int i = 0; i < strLength; i++) if (str.charAt(i) != ' ' || (length >= 0 && seq[length] != ' ')) seq[++length] = str.charAt(i); if (length == -1) return ""; // empty string if (seq[length] != ' ') return new String(seq,0,length+1); else //remove trailing blank return new String(seq,0,length); } |

.