Java程序检查字符串是否为pangram
七巧板是一个包含英语字母所有字母的字符串。一个容易打扰的例子是“敏捷的棕色狐狸跳过了懒狗”。
给出一个检查字符串是否为pangram的程序,如下所示。
示例
public class Example {
public static void main(String[] args) {
String str = "The quick brown fox jumps over the lazy dog";
boolean[] alphaList = new boolean[26];
int index = 0;
int flag = 1;
for (int i = 0; i < str.length(); i++) {
if ( str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
index = str.charAt(i) - 'A';
}else if( str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
index = str.charAt(i) - 'a';
}
alphaList[index] = true;
}
for (int i = 0; i <= 25; i++) {
if (alphaList[i] == false)
flag = 0;
}
System.out.print("String: " + str);
if (flag == 1)
System.out.print("\nThe above string is a pangram.");
else
System.out.print("\nThe above string is not a pangram.");
}
}输出结果
String: The quick brown fox jumps over the lazy dog The above string is a pangram.
现在让我们了解上面的程序。
使用for循环遍历字符串str,对于每个字母,aplhaList中的相应索引都设置为true。证明这一点的代码片段如下-
for (int i = 0; i < str.length(); i++) {
if ( str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
index = str.charAt(i) - 'A';
}else if( str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
index = str.charAt(i) - 'a';
}
alphaList[index] = true;
}此后,遍历数组alphaList。如果所有值都为true,则string为pangram,并且flag的值保持为1。但是,即使1值为false,则string也不为pangram,并且flag的值设置为0。是否为pangram。演示此过程的代码段如下所示。
for (int i = 0; i <= 25; i++) {
if (alphaList[i] == false)
flag = 0;
}
System.out.print("String: " + str);
if (flag == 1)
System.out.print("\nThe above string is a pangram.");
else
System.out.print("\nThe above string is not a pangram.");
}热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短