Java string replace all whitespaces

Java String replaceAll()

The String.replaceAll(regex, replacement) in Java replaces all occurrences of a substring matching the specified regular expression with the replacement string.

A similar method replace(substring, replacement) is used for matching the literal strings, while replaceAll() matches the regex. Note that in regular expressions, literal strings are also patterns, so replaceAll() will work with literal strings as well, in addition to regex patterns.

The syntax of the replaceAll() API is as follows:

String updatedString = thisString.replaceAll(regex, replacement);
  • thisString: the string that should be searched for substring pattern and modified.
  • regex: pattern to be searched.
  • replacement: each occurrence of the matches will be replaced with this substring.
  • updatedString: the result of the API that is the modified string.

2. String.replaceAll() Example

The following Java program demonstrates the usage of replaceAll() API.

2.1. Replace All Occurrences of a Word

The following Java program replaces all occurrences of “java” with “scala“.

String str = "how to do in java !! a java blog !!"; Assertions.assertEquals("how to do in scala !! a scala blog !!", str.replaceAll("java", "scala"));

2.2. Remove All Whitespaces

The following Java program replaces all occurrences of whitespaces in a string with an empty string.

String blog = "how to do in java"; Assertions.assertEquals("howtodoinjava", blog.replaceAll("\\s", ""));

We should know that replaceAll() throws PatternSyntaxException if the regex’s syntax is NOT valid. In the given example, “[” is an invalid regular expression, so we get the exception in runtime.

Assertions.assertThrows(PatternSyntaxException.class, () -> < blog.replaceAll("[", ""); >);

Источник

Different ways to remove Spaces from String In Java

String manipulation is done most often while programming. Like removing spaces in or around the string text. This also known as ‘strip’ping off spaces in the string. So up till now we are all aware of the different ways to remove spaces from string in java, namely trim, replaceAll. However, java 11 has made some new additions to these with methods like, strip, stripLeading , stripTrailing.

Majority of the times, we just use the trim method for removing spaces. We never stop and think is there may be a better way to suit our need? Sure, trim() works well for most of the cases, but there are many different methods in java. Each having its own advantages and disadvantages. How do we decide which method suits us best?

Well, in this blog we shall cover the different methods in detail.

Читайте также:  Python how to run unittests

Different ways to remove spaces from string in java

Most important point to note is that in java a string object is immutable. It means we cannot modify a string, hence all the methods returns new string with all the transformations.

If you need to remove leading and trailing spaces the best option would be before java 11 trim() and from java 11 strip() method.

trim() method in java

trim() is the most commonly used method by java developers for removing leading and trailing spaces. For trim method space character means any character whose ASCII value is less than or equal to 32 (‘U+0020’).

Example of trim method to remove spaces:

public class StringTrimTest < public static void main(String[] args) < String string = " String with space "; System.out.println("Before trim: \"" + string +"\""); System.out.println("After trim: \"" + string.trim() +"\""); >>
Before trim: " String with space " After trim: "String with space"

strip() method Java 11

In the release of Java 11 new strip() method was added to remove leading and trailing spaces from String.

This method was added as there are various space characters according to Unicode standards having ASCII value more than 32(‘U+0020’). Ex: 8193(U+2001).

To identify these space characters, new method isWhitespace(int) was added from Java 1.5 in Character class. This method uses unicode to identify space characters. You can read more about unicode space characters here.

The strip method uses this Character.isWhitespace(int) method to cover wide range of white space characters and remove them.

Example of strip():

public class StringStripTest < public static void main(String[] args) < String string = " String with space "; System.out.println("Before strip: \"" + string+"\""); System.out.println("After strip: \"" + string.strip()+"\""); >>
Before strip: " String with space " After strip: "String with space"

Difference between trim and strip method in java

trim() strip()
From Java 1 From Java 11
Uses codepoint(ASCII) value Uses Unicode value
Removes leading and trailing character(space) Removes leading and trailing character(space)
Removes characters having ASCII value less than or equal to ‘U+0020’ or ’32’ Removes all space characters according to unicode

Let’s look at the example where we will use white space character higher than 32 (‘U+0020’) unicode.

public class StringTrimVsStripTest < public static void main(String[] args) < String string = '\u2001'+"String with space"+ '\u2001'; System.out.println("Before: \"" + string+"\""); System.out.println("After trim: \"" + string.trim()+"\""); System.out.println("After strip: \"" + string.strip()+"\""); >>

In the above example we can see that trim method is unable to remove space character added by ‘\u2001’ unicode character.

Note: If you are running on windows machine, you may not be able to see the similar output due to limited unicode set. You can use online compilers to run program. Some online compiler links are as below,
Java-8: https://www.jdoodle.com/online-java-compiler/
Java-11: https://www.tutorialspoint.com/compile_java_online.php

stripLeading() method Java 11

Added in Java 11, stripLeading() method removes all leading spaces from a String.

Similar to strip method stripLeading also uses Character.isWhitespace(int) for identifyng white spaces.

public class StringStripLeadingTest < public static void main(String[] args) < String string = " String with space "; System.out.println("Before: \"" + string+"\""); System.out.println("After : \"" + string.stripLeading()+"\""); >>
Before: " String with space " After : "String with space "

stripTrailing() method Java 11

Added in Java 11, stripTrailing() method removes all ending spaces from a String.

Читайте также:  Тег А

Similar to strip method stripTrailing also uses Character.isWhitespace(int) for identifying white spaces.

public class StringStripTrailingTest < public static void main(String[] args) < String string = " String with space "; System.out.println("Before: \"" + string+"\""); System.out.println("After : \"" + string.stripTrailing()+"\""); >>
Before:" String with space " After :" String with space"

replace(CharSequence target, CharSequence replacement):

Added from java 1.5, This method is used to replace each target substring with the specified replacement string.

This method replaces all matching target elements. Hence replace() method can be used to remove all spaces from a string.

Note: One more method replace(char oldChar, char newChar) is present in java string class. The only differences is that this method takes single character as target and replacement. We cannot use this method to remove space, because we cannot have empty character as replacement.

Example to remove all spaces from string

public class StringReplaceTest < public static void main(String[] args) < String string = " String with space "; System.out.println("Before : \"" + string + "\""); System.out.println("Replace: \"" + string.replace(" ", "") + "\""); >>
Before : " String with space " Replace : "Stringwithspace" 

replaceAll (String regex, String replacement)

Added in java 1.4, this is one of the most powerful method for string manipulation. We can use this method for many purposes.

Using replaceAll() method we can replace each matching regular expression substring with the given replacement string. For example for removing all spaces, removing leading spaces, removing trailing spaces and so on.

We just need to create correct regular expression with correct replacement parameter. Some regular expression examples as below:

\s+ Find all space
^\s+ Find all spaces at line beginning
\s+$ Find all spaces at line ending

Example to replacing spaces in string,

Note: In java to add ‘/'(slash) we have to use escape character so for «\s+» we have to use «\\s+»

public class StringReplaceAllTest < public static void main(String[] args) < String string = " String with space "; System.out.println("Before replaceAll : \"" + string+"\""); System.out.println("Replace all space : \"" + string.replaceAll(" ", "") + "\""); System.out.println("Replace all regex : \"" + string.replaceAll("\\s+", "") + "\""); System.out.println("Replace leading : \"" + string.replaceAll("^\\s+", "") + "\""); System.out.println("Replace trailing : \"" + string.replaceAll("\\s+$", "") + "\""); >>
Before replaceAll : " String with space " Replace all space : "Stringwithspace" Replace all regex : "Stringwithspace" Replace leading : "String with space " Replace trailing : " String with space"

As we can see that replaceAll() is pretty powerful method if we use it with proper regular expression.

Difference between replaceAll and replace method

replaceAll() replace()
From Java 1.4 From Java 1.5
Accepts regular expression for target identification Accepts string for target identification
Used for fix or dynamic string replacement Used for fix string replacement
Removes characters having ASCII value less than or equal to ‘U+0020’ or ’32’ Removes all space characters according to unicode

replaceFirst(String regex, String replacement)

Added in java 1.4, replaceFirst method replaces only the first match of given regular expression with replacement string.

This method can be very useful if you just need to replace only one first occurrence. For example if we just need to remove leading spaces we can use «\\s+» or «^\\s+».

Читайте также:  Автообновление html vs code

We can also use this method to remove trailing spaces by using «\\s+$» regular expression. As this expression will only match the last spaces in line. So last spaces are considered as the first match for this method.

Let’s take an example for removing leading and trailing spaces from string

public class StringReplaceFistTest < public static void main(String[] args) < String string = " String with space "; System.out.println("Original text : \"" + string+"\""); System.out.println("Updated text : \"" + string.replaceFirst("space", "update") + "\""); System.out.println("Remove leading space: \"" + string.replaceFirst("\\s+", "") + "\""); System.out.println("Remove trailing space: \"" + string.replaceFirst("\\s+$", "") + "\""); >>
Original text : " String with space " Updated text : " String with update " Remove leading space: "String with space " Remove trailing space: " String with space"

Fast track reading :

  • There are different ways to remove spaces from string in java
  • trim() is the most common method used for removing spaces in string
  • trim method is not unicode aware and uses ascii value to identify space characters
  • From java 11 new method ‘strip()’ is added for removing spaces
  • Method strip is unicode aware and it should be used for removing spaces specially in multilingual case
  • From Java 11 methods like stripLeading() and stripTrailing() are aded for removing leading and trailing spaces.
  • For more controlled removal of spaces we can use replaceAll(), replace(), replaceFirst()

Источник

Java – Remove All White Spaces from a String

Learn to write a Java program to remove all the white spaces and non-visible characters from a given string. It may not be needed in real world applications, but it certainly can be asked in interviews to check our knowledge and reasoning.

1. Using Regular Expression

The best way to find all whitespaces and replace them with an empty string is using regular expressions. A white space is denoted with “\\s” in regex. All we have to find all such occurrences and replace them with an empty string.

Use «\\s+» if there are more than one consecutive whitespaces. It matches one or many whitespaces.

To perform this search and replace in the string, we can use String.replaceAll() method.

String sentence = " how to do in java "; System.out.println("Original sentence: " + sentence); String cleanSentence = sentence.replaceAll("\\s+", ""); System.out.println("After replacement: " + cleanSentence);
Original sentence: how to do in java After replacement: howtodoinjava

2. Using Character.isWhitespace()

Another easy way to do this search and replace is by iterating over all characters of the string.

  • Determine if the current char is white space or printable character.
  • Append all printable characters in the string and omit all white spaces.

The resulted string will be free from all white spaces.

String sentence = " how to do in java "; System.out.println("Original sentence: " + sentence); sentence = sentence.codePoints() .filter(c -> !Character.isWhitespace(c)) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); System.out.println("After replacement: " + sentence);
Original sentence: how to do in java After replacement: howtodoinjava

Drop me your questions in the comments.

Источник

Оцените статью