Normalize all whites paces from string

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the StringBuffer Class we can remove the White spaces from a string.

String normalizeWhitespaces(String s) {
		StringBuffer res = new StringBuffer();
		int prevIndex = 0;
		int currIndex = -1;
		int stringLength = s.length();
		String searchString = " ";
		while ((currIndex = s.indexOf(searchString, currIndex + 1)) >= 0) {
			res.append(s.substring(prevIndex, currIndex + 1));

			while (currIndex < stringLength && s.charAt(currIndex) == ' ') {

			prevIndex = currIndex;

		return res.toString();
nilanchala avtar

Nilanchala Panigrahy

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (