Java program to check if string is pangram


A pangram is a string that contains all the letters of the English alphabet. An example of a pangram is "The quick brown fox jumps over the lazy dog".

A program that checks if a string is pangram or not is given as follows.

Example

 Live Demo

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("
The above string is a pangram.");    else       System.out.print("
The above string is not a pangram.");    } }

Output

String: The quick brown fox jumps over the lazy dog
The above string is a pangram.

Now let us understand the above program.

The string str is traversed using a for loop and for every alphabet, the corresponding index in aplhaList is set to true. The code snippet that demonstrates this is given as follows −

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;
}

After this, the array alphaList is traversed. If all the values are true, then string is a pangram and value of flag remains 1. However, if even 1 value is false, then string is not a pangram and the value of flag is set to 0. Then it is displayed if string is pangram or not. The code snippet that demonstrates this is given as follows.

for (int i = 0; i <= 25; i++) {
   if (alphaList[i] == false)
      flag = 0;
   }
   System.out.print("String: " + str);
   if (flag == 1)
      System.out.print("
The above string is a pangram.");    else       System.out.print("
The above string is not a pangram."); }

Updated on: 25-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements