Pangram Checking in Java
In this tutorial, we will be checking if a string is a Pangram or not in Java.
So what are Pangram Strings?
Pangram
A String which contains all the 26 letters of English alphabets is called as a Pangram String.
These letters can be lowercase or uppercase.
Example 1: ” qwaserdftyghujkiolpbnmvcxz “.
The above sentence contains all the 26 letters in English.
Hence this sentence is a Pangram.
Example 2: ” guoghwec dhsjk hkjkshdgwo mcaxmnhihd “.
The above sentence doesn’t contain all the 26 English letters.
Hence this sentence is not a Pangram.
The .java file for checking if a string is a Pangram or not in Java is given below.
Code for implementing Pangram Checking in Java
import java.util.*; class pangram { public static void main(String[]args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the String: "); String s = scan.nextLine(); int[]check = new int[26]; String str = s.toLowerCase(); //to convert the entire string to lowercase for(int i = 0; i < str.length(); i++) { if(str.charAt(i) != 36 && str.charAt(i) >= 97 && str.charAt(i) <= 122) { check[str.charAt(i) - 97] = 1; } } for(int i = 0; i < 26; i++) { if(check[i] != 1) { System.out.println("Not Pangram"); System.exit(0); } } System.out.println("Pangram"); } }
Explanation
- Firstly we scan the input String and convert it into lowercase to simplify the problem.
- Next, we check each character of the string and using its ASCII value we store a value (in this case 1) in its respective array location so that we can fill the entire array with 1’s.
- In the end, after filling the array, we check if all the places in the array have been filled with 1’s or not.
Output:
Enter the String: Codespeedy.com Not pangram
Enter the String: The quick brown fox jumps over the lazy dog Pangram
Hope you’ve understood the code 🙂
Any questions please feel free to drop in your comments.
Also check out my other posts at:
Leave a Reply