Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet50/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   46   47   48   49   50   51   52   53   ...   245
Bog'liq
Java 17 Recipes

 How It Works
The String object contains many helper methods. One such method is substring(), 
which can return portions of the string. There are two variations of the substring() 
method. One of them accepts a single argument, that being the starting index. The other 
accepts two arguments: startingindex and endingindex. Having two variations of the 
substring() method makes it seem as though the second argument is optional; if it is 
not specified, the length of the calling string is used in its place. It should be noted that 
indices begin with 0, so the first position in a string has an index of 0, and so on.
As you can see from the solution to this recipe, the first use of substring() prints 
out the entire contents of the string. This is because the first argument passed to the 
substring() method is 0, and the second argument passed is the length of the original 
string. In the second example of substring(), an index of 5 is used as the first argument, 
and an index of 20 is used as the second argument. This effectively causes only a portion 
of the string to be returned, beginning with the character in the string that is located in 
the sixth position, or index 5 because the first position has an index of 0; and ending with 
Chapter 3 StringS


81
the character in the string that is located in the twentieth position, the index of 19. The 
third example specifies only one argument; therefore, the original string begins with the 
position specified by that argument.
Note the 
substring() method only accepts positive integer values. if you attempt 
to pass a negative value, a java.lang.StringIndexOutOfBoundsException 
is thrown.
3-3. Comparing Strings
 Problem
An application that you are writing needs to have the ability to compare two or more 
string values.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   46   47   48   49   50   51   52   53   ...   245




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