Thursday 28 July 2022

Replace multiple spaces between a String with single space in Java

Problem Statement

I have given following string.

Hello     there   how are    you....

 

You need to replace multiple spaces with single space and print the below string.

Hello there how are you....

 

package com.sample.app.strings;

public class StringSpaceReplacer {

	// private static String replaceMultipleSpaces(final String str) { }
	
	public static void main(String[] args) {
		String str1 = "Hello there how are you....  ";
		String str2 = "   Hello there how are you....";
		String str3 = "  Hello there how are you....  ";
		String str4 = " ";

		System.out.println("'" + replaceMultipleSpaces(str1) + "'");
		System.out.println("'" + replaceMultipleSpaces(str2) + "'");
		System.out.println("'" + replaceMultipleSpaces(str3) + "'");
		System.out.println("'" + replaceMultipleSpaces(str4) + "'");

	}

}

 

All the approaches tested against above samples. I am going to implement the method ‘replaceMultipleSpaces’ in different ways.

 

Approach 1: Using a regular expression.

 

private static String replaceMultipleSpaces(final String str) {
	if (str == null || str.isEmpty()) {
		return str;
	}

	return str.replaceAll("\\s+", " ");
}

 

Approach 2: Read character by character and compare neighboring spaces.


 

private static String replaceMultipleSpaces(final String str) {
	if (str == null || str.isEmpty()) {
		return str;
	}

	final StringBuffer builder = new StringBuffer();
	boolean isSpaceFound = false;

	for (char ch : str.toCharArray()) {

		// This will ignore continuos spaces.
		if (ch == ' ' && isSpaceFound == true) {
			continue;
		}

		if (ch == ' ') {
			isSpaceFound = true;
		} else {
			isSpaceFound = false;
		}

		builder.append(ch);

	}

	return builder.toString();
}

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment