Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- /* Define some return codes */
- #define ANAGRAM_BAD_ARGS 1
- #define ANAGRAM_DIFFERENT_LENGTHS 2
- #define ANAGRAM_DIFFERENT_STRINGS 4
- static void SortUpperCase(char *src, char *dst, int len){
- /* Returns an upper-case sorted string */
- int i, j; /* Generic counters */
- char tmp;
- for (i = 0 ; i < len ; i++) {
- *(dst+i) = toupper(*(src+i));
- }
- *(dst+len) = '\0'; /* Need to terminate new string */
- /* Bubble sort the string */
- for (i = len-1 ; i != 0 ; i--) {
- for (j = 0 ; j < i ; j++) {
- if (*(dst+j) > *(dst+i)) {
- tmp = *(dst+i);
- *(dst+i) = *(dst+j);
- *(dst+j) = tmp;
- }
- }
- }
- }
- static int CheckAnagram(char *s, char *t) {
- /*
- ** Compares s and t for equivalence by converting them
- ** to UPPERCASE and then sorting them. The two string are
- ** then compared.
- */
- int slen=strlen(s), tlen=strlen(t);
- char sbuf[slen+1], tbuf[tlen+1];
- if (slen != tlen) return ANAGRAM_DIFFERENT_LENGTHS;
- SortUpperCase(s, sbuf, slen);
- SortUpperCase(t, tbuf, tlen);
- if (strcmp(sbuf, tbuf))
- return ANAGRAM_DIFFERENT_STRINGS;
- else
- return 0;
- }
- extern int main(int argc, char **argv) {
- /*
- ** Compares two words (given as command-line
- ** arguments) to see if they are case-independent
- ** anagrams of each other.
- **
- ** Knocked out quickly as part of Google+ discussion
- ** in the C-programming thread.
- **
- ** Tim Greening-Jackson
- ** (tim@greening-jackson.com)
- ** 27 November 2014
- */
- int status;
- if (argc == 3) {
- if (status = CheckAnagram(argv[1], argv[2])) {
- printf("'%s' and '%s' are different\n", argv[1], argv[2]);
- return status;
- }
- else {
- printf("'%s' and '%s' are anagrams\n", argv[1], argv[2]);
- return 0;
- }
- } else {
- printf("Syntax: %s <word1> <word2>\n", *argv);
- return ANAGRAM_BAD_ARGS;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement