Friday, July 27, 2012

Pangram Checking Algorithm in ANSI C

A pangram is a sentence that contains at least once all the letters of the alphabet. A well known pangram in the English language is the sentence "A quick brown fox jumps over the lazy dog".

To check if a string is a pangram we must implement a flag vector containing entries for each letter of the alphabet. A flag will be set if the corresponding letter is found in the string. If all flags from the flag vector are set, then the string is pangram.

An implementation for this function would be:
/*
 * Description:
 *  Verifies is the string is a pangram
 * Parameters:
 *  string - a pointer to the string
 * Returns:
 *  true - if the word is a pangram
 *  false - if the word is not a pangram
 */
bool IsPangram(char* string)
{
   bool alphabetFlags[NUMBER_OF_LETTERS];
   int size = strlen(string);
   bool isPangram = true;
   char c;
   int i;

   /*Initializes all alphabet flags to false*/
   for(i=0; i<NUMBER_OF_LETTERS; i++)
   {
      alphabetFlags[i] = false;
   }
   /*For every unique letter the string contains an
    alphabet flag will be set to true*/
   for(i=0; i<size; i++)
   {
      c = tolower(string[i]);
      if(islower(c))
      {
         alphabetFlags[string[i]-'a']=true;
      }
   }
   /*If the string is a pangram every flag will be set to true*/
   for(i=0; (i<NUMBER_OF_LETTERS && isPangram==true); i++)
   {
      if(alphabetFlags[i]==false)
      {
         isPangram=false;
      }
   }
   return isPangram;
}
The function initializes all flags from the bool vector to false. After that, it checks every letter character from the string and sets the corresponding flag in the bool vector. If all flags are set, then the string is pangram.

Example
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<ctype.h>

#define NUMBER_OF_LETTERS 26

bool IsPangram(char* string);

int main(void)
{
   char pangram1[] = "The quick brown fox jumps over the lazy dog";
   char pangram2[] = "Bird, bird, bird! The bird is the word!";
   if(IsPangram(pangram1))
   {
      printf("<%s> is a pangram\n",pangram1);
   }
   else
   {
      printf("<%s> is not a pangram\n",pangram1);
   }
   if(IsPangram(pangram2))
   {
      printf("<%s> is a pangram\n",pangram2);
   }
   else
   {
      printf("<%s> is not a pangram\n",pangram2);
   }
   return 0;
}
/*Output
<The quick brown fox jumps over the lazy dog> is a pangram
<Bird, bird, bird! The bird is the word!> is not a pangram
 */

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger