Java program to check if a string is pangram

Hi everyone, in this blog, I will be writing about a java program to check whether a string is pangram or not. Pangrams are words or sentences containing every letter of alphabet at least once. Most commonly used example of pangram is " A quick brown fox jumps over the lazy dog. "

Logic of the program

  • Initialize a string testString as "abcdefghijklmnopqrstuvwxyz"
  • Loop the input string for every character, and replace those character in testString with empty character.
  • If testString is an empty string, then input string is Pangram

The program for pangram is as follows:

package com.blog.techjourney;

public class Pangram {
 
 public static Boolean checkForPangram(String str)
 {
  int len = str.length();
  //test string for testing all characters are present in the given string
  String testString = "abcdefghijklmnopqrstuvwxyz";
  
  for (int i=0;i<len;i++)
  {
   char chars =str.charAt(i);
   //Converting the char to String and to match with the 'testString'
   String word =Character.toString(chars).toLowerCase();
   testString = testString.replaceAll(word, "");
   
   if(testString.equals(""))
   {
    return true;
   }
  }
  return false;
 }
}

The jUnit test cases are as follows:

package com.blog.techjourney.test;

import static org.junit.Assert.*;

import org.junit.Test;

import com.blog.techjourney.Pangram;

public class testForPangram {

  //Test for strings which are pangrams
   @Test
     public void test_Pangram() 
     {
         assertTrue(Pangram.checkForPangram("Hi ABCdefghijklmnopqrstuvwxyz Hello"));
         assertTrue(Pangram.checkForPangram("Pack my box with five dozen liquor jugs."));
     }
   
   //Test for strings which are not pangrams
   @Test
     public void test_NotPangram() 
     {
         assertFalse(Pangram.checkForPangram("Not a Pangram"));
         assertFalse(Pangram.checkForPangram("This also not a pangram"));
     }

}

All the test cases were passed successfully.

Other posts in this blog

  1. Conversion of String to Int using Java
  2. Java program to convert integer to string
  3. Anonymous classes in C++

Comments

Post a Comment

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++