Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- 3-3. Comparing Strings Problem
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: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling