Friday 10 January 2020

Java: Replace 2 or more spaces with single space in a string


Approach 1: Using Regular Expression.
Below regular expressions are used to replace multiple spaces with single space.
str.replaceAll(" +", " ");
str.replaceAll("\\s{2,}", " ");
str.replaceAll("\\s+", " ");

Approach 2: Programmatically find subsequent spaces.
private static String replaceMultipleSpaces(String str) {
 StringBuilder builder = new StringBuilder();

 if (str == null || str.isEmpty()) {
  return str;
 }

 char[] charArray = str.toCharArray();

 boolean flag = false;
 for (char ch : charArray) {

  if (ch == ' ') {
   if (flag == false) {
    flag = true;
    builder.append(ch);
   }

  } else {
   builder.append(ch);
   flag = false;
  }
 }

 return builder.toString();
}

Find the below working application.


App.java
package com.sample.app;

public class App {

 private static String replaceMultipleSpaces(String str) {
  StringBuilder builder = new StringBuilder();

  if (str == null || str.isEmpty()) {
   return str;
  }

  char[] charArray = str.toCharArray();

  boolean flag = false;
  for (char ch : charArray) {

   if (ch == ' ') {
    if (flag == false) {
     flag = true;
     builder.append(ch);
    }

   } else {
    builder.append(ch);
    flag = false;
   }
  }

  return builder.toString();
 }

 public static void main(String args[]) {

  String str = "Hello   World How  Are       you?";
  String replacedStr1 = str.replaceAll(" +", " ");
  String replacedStr2 = str.replaceAll("\\s{2,}", " ");
  String replacedStr3 = str.replaceAll("\\s+", " ");
  String replacedStr4 = replaceMultipleSpaces(str);

  System.out.println("Original String : '" + str + "'");
  System.out.println("String after replacing multiple spaces with single space : '" + replacedStr1 + "'");
  System.out.println("String after replacing multiple spaces with single space : '" + replacedStr2 + "'");
  System.out.println("String after replacing multiple spaces with single space : '" + replacedStr3 + "'");
  System.out.println("String after replacing multiple spaces with single space : '" + replacedStr4 + "'");

  System.out.println("replacedStr1.equals(replacedStr2) : " + replacedStr1.equals(replacedStr2));
  System.out.println("replacedStr1.equals(replacedStr3) : " + replacedStr1.equals(replacedStr3));
  System.out.println("replacedStr1.equals(replacedStr4) : " + replacedStr1.equals(replacedStr4));
 }

}


You may like

No comments:

Post a Comment