What is the purpose of String.strip() method of Java 11?

The purpose of the String.strip() method in Java 11 is to remove whitespaces from both the beginning and end of a string. This is very similar to the String.trim() method available in earlier versions of Java, but there is a key difference between them.

Here’s the difference:

  • String.strip(): Introduced in Java 11, strip() uses the unicode definition of whitespace. It removes not only space characters but also all other types of unicode-defined spaces, such as the thin space \u2009, etc.
  • String.trim(): Available from Java 1.0, trim() is more limited. It considers a whitespace to be any character whose ASCII value is less than or equal to 32 (a space, tab, newline, and a few other control characters).

Here are examples of how they work:

package org.kodejava.lang;

public class StringStripExample {
    public static void main(String[] args) {
        // String.strip()
        String first = " \u2009Hello  ";
        System.out.println(first.strip()); // Outputs "Hello"

        // String.trim()
        String second = " \u2009Hello  ";
        System.out.println(second.trim()); // Outputs "\u2009Hello"
    }
}

Output:

Hello
 Hello

Thus, strip() method is more comprehensive in removing different types of whitespace defined in Unicode, while trim() only removes ASCII control characters and spaces.

There are also String.stripLeading() and String.stripTrailing() methods that were introduced in Java 11, and they are similar to the strip() method, but they only remove the whitespace characters from either the beginning or the end of the string, respectively.

Here is what they do:

  • String.stripLeading(): This method removes any leading whitespace from the string. “Leading” in this context means any whitespace characters at the beginning of the string.
  • String.stripTrailing(): This method removes any trailing whitespace from the string. “Trailing” in this context means any whitespace characters at the end of the string.

Both stripLeading() and stripTrailing() use the Unicode definition of whitespace, the same as strip() method.

Here are examples of how they work:

package org.kodejava.lang;

public class StringStripLeadingTrailingExample {
    public static void main(String[] args) {
        // Strip leading whitespace
        String first = " \u2009Hello World  ";
        System.out.println(first.stripLeading());  // Outputs "Hello World  "

        // Strip trailing whitespace
        String second = " \u2009Hello World  ";
        System.out.println(second.stripTrailing()); // Outputs " \u2009Hello World"
    }
}

Output:

Hello World  
  Hello World

As demonstrated, stripLeading() removed the whitespace characters from the front of the string, and stripTrailing() removed the whitespace characters from the end of the string.

While \u00A0 is technically a type of whitespace (specifically, a non-breaking space or NBSP), it isn’t considered as such by the strip(), stripLeading(), and stripTrailing() methods, which follow the Character.isWhitespace(char) method’s definition of what constitutes a whitespace character.

According to the Java documentation, the Character.isWhitespace(char) method, which the strip() methods use, considers the following characters as whitespace:

  • ‘\t’ U+0009 HORIZONTAL TABULATION
  • ‘\n’ U+000A LINE FEED
  • ‘\u000B’ U+000B VERTICAL TABULATION
  • ‘\f’ U+000C FORM FEED
  • ‘\r’ U+000D CARRIAGE RETURN
  • ‘\u001C’ U+001C FILE SEPARATOR
  • ‘\u001D’ U+001D GROUP SEPARATOR
  • ‘\u001E’ U+001E RECORD SEPARATOR
  • ‘\u001F’ U+001F UNIT SEPARATOR
  • SPACE_SEPARATOR category types

The \u2009 (thin space) and \u0020 (space) are part of SPACE_SEPARATOR category according to Unicode standard and will be correctly stripped.

The \u00A0 (non-breaking space) is actually part of a different category called the NO-BREAK_SPACE and is not considered whitespace by Character.isWhitespace(char), so it won’t be stripped.

How do I create a string of repeated characters?

The following code demonstrates how to create a string of repeated characters. We use the String.repeat(int count) method introduced in Java 11. This method takes one parameter of type int which is the number of times to repeat the string. The count must be a positive number, a negative number will cause this method to throw java.lang.IllegalArgumentException.

In the snippet below, we use the method to repeat characters and draw some triangles. We combine the repeat() method with a for loop to draw the triangles.

package org.kodejava.basic;

public class StringRepeatDemo {
    public static void main(String[] args) {
        String star = "*";
        String fiveStars = star.repeat(5);
        System.out.println("fiveStars = " + fiveStars);

        String arrow = "-->";
        String arrows = arrow.repeat(10);
        System.out.println("arrows    = " + arrows);
    }
}

The outputs of the code snippet above are:

fiveStars = *****
arrows    = -->-->-->-->-->-->-->-->-->-->
package org.kodejava.basic;

public class StringRepeatDemo {
    public static void main(String[] args) {
        String asterisk = "#";
        for (int i = 1; i <= 10; i++) {
            System.out.println(asterisk.repeat(i));
        }
}

The outputs of the code snippet above are:

#
##
###
####
#####
######
#######
########
#########
##########
package org.kodejava.basic;

public class StringRepeatDemo {
    public static void main(String[] args) {
        int height = 10;
        for (int i = 1, j = 1; i <= height; i++, j += 2) {
            System.out.println(" ".repeat(height - i) + "*".repeat(j));
        }
    }
}

The outputs of the code snippet above are:

         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

How do I remove leading and trailing white space from string?

package org.kodejava.lang;

public class TrimStringExample {
    public static void main(String[] args) {
        String text = "     tattarrattat     ";
        System.out.println("Original      = " + text);
        System.out.println("text.length() = " + text.length());

        // The trim() method will result a new string object with a leading and
        // trailing while space removed.
        text = text.trim();
        System.out.println("Result        = " + text);
        System.out.println("text.length() = " + text.length());
    }
}

The result of the code snippet above:

Original      =      tattarrattat     
text.length() = 22
Result        = tattarrattat
text.length() = 12

How do I convert string to char array?

Here we have a small class that convert a string literal into an array, a character array. To do this we can simply use String.toCharArray() method.

package org.kodejava.lang;

public class StringToArrayExample {
    public static void main(String[] args) {
        // We have a string literal that contains the tag line of this blog.
        String literal = "Kode Java - Learn Java by Examples";

        // Now we want to convert or divided it into a small array of char.
        // To do this we can simply used String.toCharArray() method. This
        // method splits the string into an array of characters.
        char[] temp = literal.toCharArray();

        // Here we just iterate the char array and print it to our console.
        for (char c : temp) {
            System.out.print(c);
        }
    }
}

How do I check a string starts with a specific word?

To test if a string starts with a specific prefix we can use the String.startsWith(String prefix) method. This method returns a boolean true as the result if the string starts with that specified prefix. The String.startsWith() method checks the prefix in case-sensitive manner.

The following code snippet give us a small example how to use this method, but instead of just straightly checks using the startsWith() method, we add a scanner that allows us to input the prefix that we want to test.

package org.kodejava.lang;

import java.util.Scanner;

import static java.lang.System.in;

public class StringStartsWithExample {
    private static final Scanner scanner = new Scanner(in);

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Text: " + text);

        System.out.print("Type the prefix to test: ");
        String search = scanner.nextLine();

        // Check if the text start with the search text.
        if (text.startsWith(search)) {
            System.out.println("Yes, the fox is the quick one");
        } else {
            System.out.println("The fox is a slow fox");
        }
    }
}

The code snippet print the following output:

Text: The quick brown fox jumps over the lazy dog
Type the prefix to test: The quick brown fox
Yes, the fox is the quick one