Java如何迭代字符串的每个字符?
以下示例说明如何使用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);
}
}
热门推荐
10 蛋糕祝福语简短闺蜜
11 春节新年祝福语简短幽默
12 祝福语大全短句简短英语
13 给妈妈祝福语简短内容
14 爸爸生日的祝福语简短
15 国庆祝福语简单简短
16 高考成绩出祝福语 简短
17 写给女友的祝福语++简短
18 生日祝福语哥哥英文简短