A string is known as pangram if it has all the alphabets from a to z at least once. A popular example of pangram sentence is “The quick brown fox jumps over the lazy dog”.
Here are some other examples of pangram sentences.
- “How vexingly quick daft zebras jump”
- “Bright vixens jump; dozy fowl quack”
- “Quick zephyrs blow, vexing daft Jim”
- “Sphinx of black quartz, judge my vow”
- “Five quacking zephyrs jolt my wax bed”
Now let’s have a look at how to check if a string is pangram in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class Pangram { public static boolean isPangram(String sentence) { // array to store the occurrence of each letter boolean[] marked = new boolean[26]; // Convert to lower case for uniformity String lowerCaseSentence = sentence.toLowerCase(); // iterate over every character in the string for (int i = 0; i < lowerCaseSentence.length(); i++) { char ch = lowerCaseSentence.charAt(i); if ('a' <= ch && ch <= 'z') { marked[ch - 'a'] = true; } } // Check if every letter occurred at least once for (boolean m : marked) { if (!m) { return false; } } return true; } public static void main(String[] args) { String sentence = "The quick brown fox jumps over the lazy dog"; if (isPangram(sentence)) { System.out.println("This is a pangram"); } else { System.out.println("This is not a pangram"); } } } |
Output:
This is a pangram
Explanation:
- First, we created a boolean array to store the occurrence of each letter. Initially, its value is false.
- We converted the string to lowercase for uniformity.
- Now we iterate through each character of the string and if it’s between a to z then we mark the corresponding index of the boolean array as true.
- After that we check each element of the boolean array, if all the elements are true then the string is pangram otherwise not.