How to remove all white spaces from a String in Java?

Given a String with void areas, the errand is to eliminate all blank areas from a string utilizing Java worked in strategies.

String API in Java gives a few utility strategies to eliminate void area from String in Java, from the start, end, and between words. Void area implies clear space including tab characters. One of the exemplary strategies to eliminate blank area from the start and end of a string in Java is the trim() technique, which eliminates void area from starting and end. While utilizing the trim() technique, the critical thing to recall is that trim() returns an alternate String object than the more established one since String is changeless in Java.

Then again, to eliminate all void areas from string for example blank area from the start, end, and between words then you can utilize the replaceAll() strategy for String and pass ordinary articulation \s to find and supplant all void areas incorporating the tab with void string “”.

This is the speediest method of eliminating all void area from String in Java. Eliminating void areas isn’t just a typical programming necessity in Java advancement yet in addition one of the normal String Interview inquiries in Java.

Indeed recollect that each time you adjust a String, regardless of whether you eliminate blank area it produces another String, and makes sure to store and utilize that. In this Java instructional exercise, we will see a Java program to eliminate all blank area from String in Java including starting and end.

Program to Remove all blank area from String in Java – Example

Here is a Java program that utilizes a standard Java library to eliminate all void areas from any String in Java. This program gives an illustration of the trim() strategy to erase void area from the start too promotion from the end.

For eliminating all blank area we have utilized customary articulation alongside the replaceAll() technique for String in Java. Normal articulation to observe void area is \s, which observes all-blank areas including tab character.

You can additionally see these Java Programming courses to learn more session fundamental Java highlights like String and Regular Expressions.

String control is done regularly while programming. Like eliminating spaces in or around the string text. This otherwise called ‘strip’ping off spaces in the string. So up till now we are generally mindful of the various ways of eliminating spaces from string in java, in particular trim, replaceAll. Notwithstanding, java 11 has made some new augmentations to these with strategies like, strip, stripLeading , stripTrailing.

Example 1: Program to Remove All Whitespaces

public class Whitespaces {

    public static void main(String[] args) {
        String sentence = "T    his is b  ett     er.";
        System.out.println("Original sentence: " + sentence);

        sentence = sentence.replaceAll("\\s", "");
        System.out.println("After replacement: " + sentence);
    }
}

Output

Original sentence: T    his is b  ett     er.
After replacement: Thisisbetter.

In the above program, we use String’s replaceAll() method to remove and replace all whitespaces in the string sentence.

We’ve used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in the string. Then, we replace it with "" (empty string literal).


Example 2: Take string from users and remove the white space

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    // create an object of Scanner
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the string");

    // take the input
    String input = sc.nextLine();
    System.out.println("Original String: " + input);

    // remove white spaces
    input = input.replaceAll("\\s", "");
    System.out.println("Final String: " + input);
    sc.close();
  }
}

Output

Enter the string
J  av  a-  P rog  ram  m ing
Original String: J  av  a-  P rog  ram  m ing
Final String: Java-Programming

Greater part of the occasions, we simply utilize the trim technique for eliminating spaces. We never pause and believe is there might be a superior method for fitting our need? Indeed, trim() functions admirably for a large portion of the cases, however there are various strategies in java. Each enjoying its own benefits and hindrances. How would we conclude which strategy suits us best?

All things considered, in this blog we will cover the various strategies exhaustively.

Various ways of eliminating spaces from string in java

  1. public class RemoveAllSpace {
  2.     public static void main(String[] args) {
  3.         String str = “India     Is My    Country”;
  4.         //1st way
  5.         String noSpaceStr = str.replaceAll(“\\s”“”); // using built in method
  6.         System.out.println(noSpaceStr);
  7.         //2nd way
  8.         char[] strArray = str.toCharArray();
  9.         StringBuffer stringBuffer = new StringBuffer();
  10.         for (int i = 0; i < strArray.length; i++) {
  11.             if ((strArray[i] != ‘ ‘) && (strArray[i] != ‘\t’)) {
  12.                 stringBuffer.append(strArray[i]);
  13.             }
  14.         }
  15.         String noSpaceStr2 = stringBuffer.toString();
  16.         System.out.println(noSpaceStr2);
  17.     }
  18. }

Live Demo

import java.io.*;
public class Test {
   public static void main(String args[]) {
      String Str = new String("Hi how are you Welcome to Tutorialspoint.com");
      System.out.print("Return Value :" );
      System.out.println(Str.replaceAll(" ", ""));
   }
}

Output

Return Value :HihowareyouWelcometoTutorialspoint.com

Quick track perusing :

  • There are various ways of eliminating spaces from string in java
    trim() is the most widely recognized technique utilized for eliminating spaces in string
    trim technique isn’t unicode mindful and utilizes ascii worth to recognize space characters
  • From java 11 new strategy ‘strip()’ is added for eliminating spaces
  • Strategy strip is unicode mindful and it ought to be utilized for eliminating spaces uncommonly in multilingual case
  • From Java 11 strategies like stripLeading() and stripTrailing() are aded for eliminating driving and following spaces.

For more controlled expulsion of spaces we can utilize replaceAll(), supplant(), replaceFirst()

Also Read: GDB (Step by Step Introduction)

Leave a Reply

Your email address will not be published. Required fields are marked *