Manipulating strings is something you often encounter in programming, such as handling whitespace in strings. So far, Java has provided a number of different methods for removing whitespace from strings, namely trim, replaceAll. However, Java 11 adds some functional extensions to these methods with methods such as strip, stritrailing, and stripTrailing.

In most cases, we just use the trim() method to remove whitespace. Sometimes we can’t help but stop and think is there a better way to meet our needs? Of course, trim() works fine in most cases, but there are many different approaches in Java. Each has its own advantages and disadvantages.

In this article, you’ll detail different ways to remove whitespace from strings in Java

  • Trim () : Removes prefix and postfix Spaces from the string

  • Strip () : Removes Spaces at the beginning and end of the string. The strip() method supports the Unicode character set

  • Trim vs Strip: The difference between trim and strip methods

  • StripLeading () : Remove Spaces from the start of the string only

  • StripTrailing () : Removes only Spaces from the end of the string

  • Replace () : Replaces all target characters with new characters

  • ReplaceAll () : Replaces all regular matched characters with new characters

  • ReplaceFirst () : Replaces the first successful match with a new replacement string

  • The most important thing to note is that string objects are immutable in Java. This means that we cannot modify the string, so all methods will return a new string through all conversions.

The trim () method

Trim () is the most common method used by Java developers to remove leading and trailing whitespace. For the trim() method, a space character is any character with *ASCII value less than or equal to 32(‘U + 0020’)*.

public class FunTester {
 
    public static void main(String[] args) {
        String string = " one two three ";
        System.out.println("Original string: \"" + string +"\" ");
        System.out.println("Result: \"" + string.trim() +"\" "); }}Copy the code

Console output:

Original string: "one two three"Copy the code

Strip () method

In the Java 11 release, a new strip() method was added to remove prefix and postfix Spaces from strings.

This method was added because, according to the Unicode standard, there are various space characters with ASCII values greater than 32(‘U + 0020’). For example, 8193(U + 2001). To recognize these whitespace characters, Java 1.5 added a new method isWhitespace(int) from the Character class. This method uses Unicode to recognize space characters. The strip() method uses this character.iswhitespace (int) method to override broad whitespace characters and remove them.

public class StringStripTest {
    public static void main(String[] args) {
        String string = " one two three ";
        System.out.println("Original string: \"" + string+"\" ");
        System.out.println("Result: \"" + string.strip()+"\" "); }}Copy the code

Console output:

Original String: "String with space"Copy the code

The difference between trim and strip methods in Java

trim() strip()
From the Java 1 From the Java 11
Use ASCII value Using the Unicode value
Remove prefix and postfix characters (Spaces) Remove prefix and postfix characters (Spaces)
Deletes characters whose ASCII value is less than or equal to ‘U+0020′ or ’32’ Remove all space characters according to Unicode
  • Let’s look at using greater than32('U+0020')theunicodeWhitespace character.
public class StringTrimVsStripTest {
    public static void main(String[] args) {
        String string = '\u2001'+"one two three"+ '\u2001';
        System.out.println("Original string: \"" + string+"\" ");
        System.out.println("Result: \"" + string.trim()+"\" ");
        System.out.println("Result: \"" + string.strip()+"\" "); }}Copy the code

Console output:

Original string: "one two three"Copy the code

In the example above, we can see that the trim() method cannot remove whitespace characters added by the **’\u2001’Unicode** character.

  • Note: If running on a Windows computer, due to limitationsunicodeSettings, you may not see similar output.

StripLeading () method

The stripLeading() method was added in Java 11 to remove all prefix Spaces from String. Similar to the strip() method, stripLeading() also identifies blank characters using character.iswhitespace (int).

public class StringStripLeadingTest {
    public static void main(String[] args) {
        String string = " one two three ";
        System.out.println("Original string: \"" + string+"\" ");
        System.out.println("Result: \"" + string.stripLeading()+"\" "); }}Copy the code

Console output:

Original string: "one two three"Copy the code

StripTrailing () method

In Java 11, the stripTrailing() method was added to remove all trailing Spaces from strings. Similar to the stripTrailing() method, stripTrailing() also identifies blank using character.iswhitespace (int).

public class StringStripTrailingTest { public static void main(String[] args) { String string = " one two three "; System.out.println(" original string: \"" + string+"\""); System. The out. Println (" processing result: \ "" + string. StripTrailing () +" \ ""); }}Copy the code

Console output:

Original string :" one two three"Copy the code

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 matched target characters.

  • Note:javaIn theStringClass provides another methodReplace (char oldChar, char newChar). The difference is that the method arguments are characters, not strings.
public class StringReplaceTest {
  
    public static void main(String[] args) {
        String string = " one two three ";
        System.out.println("Original string: \"" + string + "\" ");
        System.out.println("Result: \"" + string.replace(""."") + "\" "); }}Copy the code

Console output:

Original string: "One twothree"Copy the code

replaceAll(String regex, String replacement)

Added in Java 1.4, this is one of the most powerful string manipulation methods. Using the replaceAll() method, we can replace each matched regular expression string with a given replacement string. For example, delete all Spaces, delete leading Spaces, delete trailing Spaces, and so on. We just need to create the correct regular expression with the correct substitution arguments. Reference: Java and Groovy re usage.

  • To add a ‘/’ in Java, we must use an escape character, so for\s+, must be used\\s+
public class StringReplaceAllTest {
    public static void main(String[] args) {
        String string = " one two three ";
        System.out.println("Original string: \"" + string+"\" ");
        System.out.println("Result: \"" + string.replaceAll(""."") + "\" ");
        System.out.println("Result: \"" + string.replaceAll("\\s+"."") + "\" ");
        System.out.println("处理结果  : \"" + string.replaceAll("^\\s+"."") + "\" "); 
        System.out.println("Result: \"" + string.replaceAll("\\s+$"."") + "\" "); }}Copy the code

Console output:

Original string: "One with three" Handling result:" Onetwothree "handling result:" One twothree" handling result: "One twothree"Copy the code

replaceFirst(String regex, String replacement)

In Java 1.4, the replaceFirst() method was added to replace the first occurrence of a given regular expression with a replacement string. For example, if we only need to remove prefix Spaces, we can use \\s+ or ^\\s+. You can also use this method to remove postfix Spaces by using the \\ S +$regular expression.

public class StringReplaceFistTest {
      public static void main(String[] args) {
      String string = " one two three ";
      System.out.println("Original string: \"" + string+"\" ");
        System.out.println("处理结果  : \"" + string.replaceFirst("three"."four") + "\" ");
        System.out.println("处理结果  : \"" + string.replaceFirst("\\s+"."") + "\" ");
        System.out.println("Result: \"" + string.replaceFirst("\\s+$"."") + "\" "); }}Copy the code

Console output:

Original string: "one two three" one two four "One two three"Copy the code

The public,FunTesterThe first, original sharing enthusiasts, Tencent cloud and nuggets community home page recommendation, Zhihu seven level original author, welcome to pay attention to, exchange, prohibit the third party without permission to reprint.

FunTester hot text selection

  • Function This interface is used to test albums
  • Performance Testing Topics
  • Programming thinking for everyone
  • 2020 Tester self-improvement
  • Fiddler Everywhere is the future
  • Test development engineer work skills
  • Fiddler Everywhere answers questions
  • Selenium4 IDE, it’s finally here
  • Basic elements of a quality management plan