Check if a String is a Pangram in Java – 在Java中检查一个字符串是否是Pangram

最后修改: 2019年 1月 8日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we will learn to check, if a given string is valid pangram or not using a simple Java program. A pangram is any string that contains all letters of a given alphabet set at least once.

在本教程中,我们将学习使用一个简单的Java程序来检查一个给定的字符串是否是有效的pangram。pangram是指至少包含一个给定字母集的所有字母的任何字符串。

2. Pangrams

2.盘古开天地

Pangrams are applicable to not only English language, but also to any other language having a fixed character set.

Pangrams不仅适用于英语,而且也适用于任何其他具有固定字符集的语言。

For example, a commonly known English pangram is “A quick brown fox jumps over the lazy dog”. Similarly, these are available in other languages, too.

例如,常见的英语pangram是 “一只快速的棕色狐狸跳过懒惰的狗”。同样,在其他语言中也有这种情况。

3. Using a for Loop

3.使用for循环

First, let’s try a for loop. We’ll populate a Boolean array with markers for each character of the alphabet.

首先,让我们尝试一个for loop我们将用字母表中每个字符的标记来填充一个Boolean 数组。

The code returns true when all the values in the marker array are set to true:

当标记数组中的所有值都被设置为true时,该代码返回true

public static boolean isPangram(String str) {
    if (str == null) {
        return false;
    }
    Boolean[] alphabetMarker = new Boolean[ALPHABET_COUNT];
    Arrays.fill(alphabetMarker, false);
    int alphabetIndex = 0;
    str = str.toUpperCase();
    for (int i = 0; i < str.length(); i++) {
        if ('A' <= str.charAt(i) && str.charAt(i) <= 'Z') {
            alphabetIndex = str.charAt(i) - 'A';
            alphabetMarker[alphabetIndex] = true;
        }
    }
    for (boolean index : alphabetMarker) {
        if (!index) {
            return false;
        }
    }
    return true;
}

Let’s test our implementation:

让我们测试一下我们的实现。

@Test
public void givenValidString_isPanagram_shouldReturnSuccess() {
    String input = "Two driven jocks help fax my big quiz";
    assertTrue(Pangram.isPangram(input));  
}

4. Using Java Streams

4.使用Java Streams

An alternate approach involves using the Java Streams API. We can create a filtered character stream out of the given input text and create an alphabet Map using the stream.

另一种方法是使用Java Streams API。我们可以从给定的输入文本中创建一个过滤的字符流,并使用该流创建一个字母表Map

The code returns success if the size of the Map is equal to the size of the alphabet. For English, the expected size is 26:

如果Map的大小等于字母表的大小,则代码返回成功。对于英语,预期的大小是26。

public static boolean isPangramWithStreams(String str) {
    if (str == null) {
        return false;
    }
    String strUpper = str.toUpperCase();

    Stream<Character> filteredCharStream = strUpper.chars()
      .filter(item -> ((item >= 'A' && item <= 'Z')))
      .mapToObj(c -> (char) c);

    Map<Character, Boolean> alphabetMap = 
      filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1));

    return alphabetMap.size() == ALPHABET_COUNT;
}

And, of course, let’s test:

当然,我们也要进行测试。

@Test
public void givenValidString_isPangramWithStreams_shouldReturnSuccess() {
    String input = "The quick brown fox jumps over the lazy dog";
    assertTrue(Pangram.isPangramWithStreams(input));
}

5. Modifying for Perfect Pangrams

5.修改以获得完美的盘口

A perfect pangram is a little bit different than a regular pangram.  A perfect pangram consists of each letter of the alphabet exactly once as opposed to at least once for a pangram.

完美七巧板与普通七巧板有一点不同。 一个完美的七巧板由每个字母正好一次组成,而一个七巧板则至少有一次。

The code returns true when both the Map size equals the alphabet size and the frequency of each character in the alphabet is exactly one:

Map的大小等于字母表的大小,并且字母表中每个字符的频率正好为1时,代码返回true

public static boolean isPerfectPangram(String str) {
    if (str == null) {
        return false;
    }
    String strUpper = str.toUpperCase();

    Stream<Character> filteredCharStream = strUpper.chars()
        .filter(item -> ((item >= 'A' && item <= 'Z')))
        .mapToObj(c -> (char) c);
    Map<Character, Long> alphabetFrequencyMap = 
      filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return alphabetFrequencyMap.size() == ALPHABET_COUNT && 
      alphabetFrequencyMap.values().stream().allMatch(item -> item == 1);
}

And let’s test:

并让我们进行测试。

@Test
public void givenPerfectPangramString_isPerfectPangram_shouldReturnSuccess() {
    String input = "abcdefghijklmNoPqrStuVwxyz";
    assertTrue(Pangram.isPerfectPangram(input));
}

A perfect pangram should have each character exactly once. So, our previous pangram should fail:

一个完美的七巧板应该是每个字符都正好有一次。因此,我们之前的pangram应该失败。

String input = "Two driven jocks help fax my big quiz";
assertFalse(Pangram.isPerfectPangram(input));

In the above code, the given string input has several duplicates, like it has two o’s. Hence the output is false.

在上面的代码中,输入的字符串有几个重复的,比如有两个O。因此,输出结果是false

5. Conclusion

5.总结

In this article, we’ve covered various solution approaches to find out whether a given string is a valid pangram or not.

在这篇文章中,我们已经介绍了各种解决方法,以找出一个给定的字符串是否是一个有效的pangram。

We also discussed one other flavor of pangrams which is called perfect pangram & how to identify it programmatically.

我们还讨论了pangrams的另一种风味,即所谓的完美pangram以及如何以编程方式识别它。

The code sample is available over on GitHub.

该代码样本可在GitHub上获得