Problem: Write a Java program to check whether the sentence or string is Pangram or not.

Example:

Input:  The quick brown fox jumps over the lazy dog
Output: Pangram

Input:  Pencil Programmer
Output: Not Pangram

A pangram or holoalphabetic sentence is a sentence using every letter of a given alphabet at least once. The best-known English pangram is “The quick brown fox jumps over the lazy dog“.

Wikipedia

A sentence or word is called a pangram if it contains all 26 letters of the English alphabet.

To check if a string is a pangram, we need to verify whether it contains all the English alphabets.

In Java, we can easily do so by counting the frequency of each letter in the given string.

For this, we loop through the characters of the given string and store the frequency of letters in an array of size 26 (each index of the array will represent an English alphabet and the corresponding value, its frequency in the given string).

Pangram check using array

If all the elements in the array are greater than 0, then the string can be verified as a pangram string otherwise not.

import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
 
    System.out.println("Enter a sentence/string:");
    String str= in.nextLine();
 
    //Array to store counts of 26 alphbets
    int count[] = new int[26];
    boolean flag = true;        //Assuming sentence is pangram
    char ch;
 
    //Loop through each character of a string
    for(int i=0; i<str.length(); i++){
        ch = str.charAt(i);
        
        if(ch == ' ')
        continue;
        
        /*
          *check if the character is among 26 alphabets, If so
          *then increment the count of their respective index position
          'A'-'A' = 0
          'B'-'A' = 1
          'b'-'a' = 1
          'c'-'a' = 2
         */
        if(ch>='A' && ch<='Z'){
            count[ch-'A']++;      
        } else if(ch>='a' && ch<='z'){
            count[ch-'a']++;      
        }
 
    }
 
    //checking if count array has any zeros
    for(int i=0; i<count.length; i++){
      if(count[i] == 0){
        flag = false;    //Not Pangram so break
        break;
      }
    }
 
    if(flag)
      System.out.println("Pangram");
    else 
      System.out.println("Not a Pangram String");
 
  }
}

Output:

Enter a sentence/string:
The quick brown fox jumps over the lazy dog
Pangram

Leave a Reply

four × one =