Skip to content
Home » Java Programs » Remove Whitespace From String Java

Remove Whitespace From String Java

Simple remove whitespace from string java. In this program, you’ll learn how to use regular expressions in Java to eliminate all whitespace from a string. To follow along with this example, you need be familiar with the Java programming language.

String Definition in Java

The String class’s replaceAll() method substitutes the given replacement for each substring of this string that matches the given regular expression. By replacing ” ” with “, you can remove white spaces from a string. 

The replaceAll() method of the Java String class returns a string that replaces all the characters that match regex and replacement string.

String in Java Program

A Java string is a collection of characters that exists as a java.lang object. The string class in Java is used to create and manipulate strings. A string’s value cannot be changed once it has been created.

Strings are a collection of characters that are commonly used in Java programming. Strings are objects in the Java programming language. String is a Java platform class that allows you to create and manipulate strings.

Replace and Replaceall() in Java

The replace() and replaceAll() methods differ in that the replace() method replaces all occurrences of old char with new char, whereas the replaceAll() method replaces all occurrences of old string with new string.

The replaceAll() method of the Java String class returns a string that replaces all the characters that match regex and replacement string. The replace() and replaceAll() methods differ in that the replace() method replaces all occurrences of old char with new char, whereas the replaceAll() function replaces all occurrences of old string with new string.

Regex in Java

Java Regex, also known as Regular Expression, is an API that allows you to define a pattern for searching or manipulating strings. It’s commonly used to specify constraints on strings like password and email validation. You can use the Java Regex Tester Tool to test your regular expressions after learning Java regex tutorial.

All types of text search and text replace operations can be performed with regular expressions. Although Java lacks a built-in Regular Expression class, we can work with regular expressions by importing the java. util. regex package. 

Remove Whitespace From String Java

public class Main
{
public static void main(String[] args)
{
String sentence = " welcome to in rn. om";
System.out.println("Original sentence" + sentence);
sentence = sentence.replaceAll("\\s","");
System.out.println("After replacement" + sentence);
}
}

Output:

Original sentence: welcome to in rn. om
After replacement: welcometoinrn.om