Tutorials Java Normalize all whites paces from string

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();
Inline Feedbacks
View all comments
Previous Post
Android Tutorials Javatechig

Download Image using AsyncTask in Android

Next Post
Android Tutorials

Android ListView Example

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
Would love your thoughts, please comment.x