Java Reference
In-Depth Information
You can also extract a substring as an array of characters using the method getChars() , but in this case
you do need to create an array that is large enough to hold the characters and pass it as an argument to
the method. Of course, you can reuse a single array to store characters when you want to extract and pro-
cess a succession of substrings one at a time and thus avoid having to repeatedly create new arrays. Of ne-
cessity, the array you are using must be large enough to accommodate the longest substring. The method
getChars() expects four arguments. In sequence, these are:
• The index position of the first character to be extracted from the string (type int )
• The index position following the last character to be extracted from the string (type int )
• The name of the array to hold the characters extracted (type char[] )
• The index of the array element to hold the first character (type int )
You could copy a substring from text into an array with the following statements:
String text = "To be or not to be";
char[] textArray = new char[3];
text.getChars(9, 12, textArray, 0);
This copies characters from text at index positions 9 to 11 inclusive, so textArray[0] is 'n' , textAr-
ray[1] is 'o' , and textArray[2] is 't' .
Using the Collection-Based for Loop with a String
You can't use a String object directly as the source of values for a collection-based for loop, but you have
seen already that you can use an array. The toCharArray() method therefore provides you with a way to
iterate over the characters in a string using a collection-based for loop. Here's an example:
String phrase = "The quick brown fox jumped over the lazy dog.";
int vowels = 0;
for(char ch : phrase.toCharArray()) {
ch = Character.toLowerCase(ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++vowels;
}
}
System.out.println("The phrase contains " + vowels + " vowels.");
This fragment calculates the number of vowels in the String phrase by iterating over the array of type
char[] that the toCharArray() method for the string returns. The result of passing the value of the loop
variable ch to the static toLowerCase() method in the Character class is stored back in ch . Of course, you
could also use a numerical for loop to iterate over the element's characters in the string directly using the
charAt() method.
Obtaining the Characters in a String as an Array of Bytes
You can extract characters from a string into a byte[] array using the getBytes() method in the class
String . This converts the original string characters into the character encoding used by the underlying op-
erating system — which is usually ASCII. For example:
Search WWH ::




Custom Search