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.");
}热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬