Java 17 Recipes


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

3-4. Trimming Whitespace
 Problem
One of the strings you are working with contains some whitespace on either end. You 
want to get rid of that whitespace.
 Solution
Use the string trim() method to eliminate the whitespace. In the following example, a 
sentence is printed, including whitespace on either side. The same sentence is then printed 
again using the trim() method to remove the whitespace so that the changes can be seen.
String myString = " This is a String that contains whitespace. ";
System.out.println(myString);
System.out.println(myString.trim());
The output print as follows.
This is a String that contains whitespace.
This is a String that contains whitespace.
 How It Works
Regardless of how careful we are, whitespace can always become an issue when working 
with strings of text. This is especially the case when comparing strings against matching 
values. If a string contains an unexpected whitespace character, that could be disastrous 
for a pattern-searching program. Luckily, the Java String object contains the trim() 
method that can automatically remove whitespace from each end of any given string.
Chapter 3 StringS


86
The trim() method is very easy to use. As you can see from the solution to this 
recipe, all that is required to use the trim() method is a call against any given string. 
String objects contain many helper methods, making them very easy to work with. After 
all, strings are one of the most commonly used data types in any programming language
so they’d better be easy to use! The trim() method returns a copy of the original string 
with all leading and trailing whitespace removed. If, however, there is no whitespace to 
be removed, the trim() method returns the original string instance. It does not get much 
easier than that!

Download 3.2 Mb.

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




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