Java 17 Recipes
-12. Iterating Over the Characters of a String
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
3-12. Iterating Over the Characters of a String
Problem You want to iterate the characters in a string of text so that you can manipulate them at the character level. Solution Use a combination of string helper methods to access the string at a character level. If you use a string helper method within the context of a loop, you can easily traverse a string by character. In the following example, the string named str is broken down using the toCharArray() method. String str = "Break down into chars"; System.out.println(str); for (char chr : str.toCharArray()){ System.out.println(chr); } Chapter 3 StringS 96 The same strategy could be used with the traditional for loop. An index could be created to allow access to each character of the string using the charAt() method. for (int x = 0; x <= str.length()-1; x++){ System.out.println(str.charAt(x)); } Both solutions yield the following result. B r e a k d o w n i n t o c h a r s Note the first example using toCharArray() generates a new character array. therefore, the second example, using the traditional for loop, might perform faster. Chapter 3 StringS 97 How It Works String objects contain methods that can be used for performing various tasks. The solution to this recipe demonstrates a number of different String methods. The toCharArray() method can be called against a string in order to break it into characters and then store those characters in an array. This method is very powerful, and it can save a bit of time when performing this task is required. The result of calling the toCharArray() method is a char[], which can then be traversed using an index. Such is the case in the solution to this recipe. An enhanced for loop iterates through the contents of the char[] and print out each of its elements. The length() method finds the number of characters contained within a string. The result is an int value that can be very useful in the context of a for loop, as demonstrated in the solution to this recipe. In the second example, the length() method finds the number of characters in the string so that they can be iterated using the charAt() method. The charAt() method accepts an int index value as an argument and returns the character that resides at the given index in the string. Often the combination of two or more String methods can obtain various results. In this case, using the length() and charAt() methods within the same code block provided the ability to break down a string into characters. 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