以下示例说明如何使用java.text.CharacterIterator和迭代字符串中的每个字符,并java.text.StringCharacterIterator计算字符串中的元音和辅音的数量。package org.nhooo.example.text;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class StringCharacterIteratorExample {
private static final String text =
"The quick brown fox jumps over the lazy dog";
public static void main(String[] args) {
CharacterIterator it = new StringCharacterIterator(text);
int vowels = 0;
int consonants = 0;
// 从开始到最后一个字符迭代字符集
for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels = vowels + 1;
} else if (ch != ' ') {
consonants = consonants + 1;
}
}
System.out.println("Number of vowels: " + vowels);
System.out.println("Number of consonants: " + consonants);
}
}