Home > Daily Life > Format a string: remove redundant space characters

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);
	}
Categories: Daily Life Tags:
  1. June 22nd, 2010 at 10:34 | #1

    Keep up the good work, I like your writing.

  2. July 7th, 2010 at 14:20 | #2

    I want to post quick hello and want to say appriciate for this good article. Xh2XQ3H6AB25Qr

  1. May 12th, 2010 at 12:30 | #1