Advertisement
TimGJ

C anagram example

Nov 27th, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. /* Define some return codes */
  6. #define ANAGRAM_BAD_ARGS          1
  7. #define ANAGRAM_DIFFERENT_LENGTHS 2
  8. #define ANAGRAM_DIFFERENT_STRINGS 4
  9.  
  10. static void SortUpperCase(char *src, char *dst, int len){
  11.   /* Returns an upper-case sorted string */
  12.  
  13.   int i, j; /* Generic counters */
  14.   char tmp;
  15.  
  16.   for (i = 0 ; i < len ; i++) {
  17.     *(dst+i) = toupper(*(src+i));
  18.   }
  19.   *(dst+len) = '\0'; /* Need to terminate new string */
  20.  
  21.   /* Bubble sort the string */
  22.  
  23.   for (i = len-1 ; i != 0 ; i--) {
  24.     for (j = 0 ; j < i ; j++) {
  25.       if (*(dst+j) > *(dst+i)) {
  26.     tmp = *(dst+i);
  27.     *(dst+i) = *(dst+j);
  28.     *(dst+j) = tmp;
  29.       }
  30.     }
  31.   }
  32. }
  33.  
  34. static int CheckAnagram(char *s, char *t) {
  35.   /*
  36.   ** Compares s and t for equivalence by converting them
  37.   ** to UPPERCASE and then sorting them. The two string are
  38.   ** then compared.
  39.   */
  40.  
  41.   int slen=strlen(s), tlen=strlen(t);
  42.   char sbuf[slen+1], tbuf[tlen+1];
  43.  
  44.   if (slen != tlen) return ANAGRAM_DIFFERENT_LENGTHS;
  45.   SortUpperCase(s, sbuf, slen);
  46.   SortUpperCase(t, tbuf, tlen);
  47.   if (strcmp(sbuf, tbuf))
  48.     return ANAGRAM_DIFFERENT_STRINGS;
  49.   else
  50.     return 0;
  51. }
  52.  
  53. extern int main(int argc, char **argv) {
  54.   /*
  55.   ** Compares two words (given as command-line
  56.   ** arguments) to see if they are case-independent
  57.   ** anagrams of each other.
  58.   **
  59.   ** Knocked out quickly as part of Google+ discussion
  60.   ** in the C-programming thread.
  61.   **
  62.   ** Tim Greening-Jackson
  63.   ** (tim@greening-jackson.com)
  64.   ** 27 November 2014
  65.   */
  66.  
  67.   int status;
  68.   if (argc == 3) {
  69.     if (status = CheckAnagram(argv[1], argv[2])) {
  70.       printf("'%s' and '%s' are different\n", argv[1], argv[2]);
  71.       return status;
  72.     }
  73.     else {
  74.       printf("'%s' and '%s' are anagrams\n", argv[1], argv[2]);
  75.       return 0;
  76.     }
  77.   } else {
  78.     printf("Syntax: %s <word1> <word2>\n", *argv);
  79.     return ANAGRAM_BAD_ARGS;
  80.   }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement