Hackerss.com

Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in
hackerss
hackerss

Posted on

How to remove whitespaces from string in Java

How to remove whitespaces from string - Java:


package com.javadoc;

/**
* This class is used to remove whitespaces from string.
* @author javadoc
* @version 1.0
* @since 1.8
*/
public class RemoveWhitespaces {
   /**
   * This method remove whitespaces from string.
   * @param str String to remove whitespaces.
   * @return String Obtains the string without whitespaces.
   */   
   public String removeWhitespaces(String str) {
       //Variable to store the string without whitespaces
       String strWithoutSpaces = "";
       //Remove whitespaces from string
       strWithoutSpaces = str.replaceAll("\\s", "");
       //Return the string without whitespaces
       return strWithoutSpaces;
   }

   /**
   * One Example
   */
   public static void main(String args[]) throws IOException {

      RemoveWhitespaces  removeWhitespaces= new RemoveWhitespaces ();
      //Example
      String strWithoutSpaces = removeWhitespaces.removeWhitespaces("Hello World");
      //Output
      System.out.println("String without whitespaces :" + strWithoutSpaces); //HelloWorld
   }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)