Java 17 Recipes


-5. Discovering Blank Strings


Download 3.2 Mb.
Pdf ko'rish
bet54/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   50   51   52   53   54   55   56   57   ...   245
Bog'liq
Java 17 Recipes

3-5. Discovering Blank Strings
 Problem
You want to know if the string is empty or contains whitespace.
 Solution
Use the java.lang.String.isBlank() method that returns a Boolean variable.
boolean blank = string.isBlank();
In the following examples, the method returns true only when the strings are empty 
or have only whitespace characters.
The following is an example.
System.out.println("".isBlank());
prints True in the Console pane, while:
System.out.println(" ".isBlank());
prints True in the Console pane:
but:
System.out.println("Luciano Manelli".isBlank());
prints False in the Console pane.
 How It Works
Before Java 11, there was only the java.lang.String.isEmpty() method, which checks 
if this string is empty. It returns true if the length is 0; otherwise, it is false.
Chapter 3 StringS


87
The following is an example.
System.out.println("".isEmpty());
prints True in the Console pane, while:
System.out.println(" ".isEmpty());
prints False in the Console pane.
In Java 11 the new isBlank() method is equal to trim().isEmpty().
3-6. Stripping Whitespace
 Problem
You want to remove whitespace.
 Solution
Use the java.lang.String.strip() method, which deletes whitespaces, as shown in 
Listing 
3-1
.
Listing 3-1. Using the strip Method
class StripClassExample
{
public static void main(String[] args)
{
String nameString = " Ciao Sara! ";
System.out.println( nameString.strip() );
System.out.println( nameString.stripLeading() );
System.out.println( nameString.stripTrailing() );
}
}
It returns the following output.
//"Ciao Sara!"
//"Ciao Sara! "
//" Ciao Sara!"
Chapter 3 StringS


88
 How It Works
The strip method was introduced in Java 11 to remove the whitespace from both
beginning and the end of the string. It produces the same result of trim(), while 
stripLeading() removes the whitespace from the beginning and stripTrailing() removes 
the whitespace from the end.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   50   51   52   53   54   55   56   57   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling