Check if two Strings are anagrams of each other.

Code Snippets 4 U
#include < stdio.h > 
#include < stdlib.h > 
#include < string.h >

  #define true 1# define false 0
int main() {
  char * str = "Hi";
  char * str2 = "Hi";
  // for ASCII characters only
  static int strCount[256];
  static int str2Count[256];

  // easy check for anagram
  if (strlen(str) != strlen(str2)) {
    printf("Not an anagram");
    return 0;
  }
  // we have to do more checks if we are here

  for (int i = 0; i < strlen(str); i++) {
    ++strCount[ * (str + i)];
    ++str2Count[ * (str2 + i)];
  }
  int isAnagram = true;
  for (int i = 0; i < 256; i++) {
    if (strCount[i] != str2Count[i]) {
      isAnagram = false;
      break;
    }
  }
  if (isAnagram) printf("Anagram");
  else printf("Not anagram");
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

sixty three − fifty nine =