【问题标题】:print out if the two inputs are anagrams of each other or not打印出两个输入是否是彼此的字谜
【发布时间】:2013-03-19 21:16:08
【问题描述】:

我的程序从用户那里获取两个输入,并确定它们是否是彼此的字谜到目前为止,我得到了输入并按字母顺序对它们进行排序,但不确定如何比较它们以打印出它们是否相同或不是我的代码,显然 string==strings 不正确

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sort_string(char*);

int main()
{
    char string[100];
    char strings[100];

printf("\nThis program will ask you for 2 words and compare them to see if they are anagrams of each other\n\n");


printf("Enter first word\n");
gets(string);

sort_string(string);

/*commented out for testing of function*/
/*printf("%s\n", string);*/

printf("Enter  second word for comparison\n");
gets(strings);
sort_string(strings);
/*commented out for testing of function*/
/*printf("%s\n", strings);*/


if (sizeof string==sizeof strings)
    printf("\nThe two words ARE  anagrams of each other.\n");
else
    printf("\nThe two words are NOT anagrams of each other.\n");


printf("\nThank You %d  %d\n\n",sizeof string, sizeoof strings);



   return 0;
}



/*function to sort in alphabetical order to be used for comparison*/ 
void sort_string(char *s)
{
   int c, d = 0, length;
   char *pointer, *result, ch;

   length = strlen(s);

   result = (char*)malloc(length+1);

   pointer = s;

   for ( ch = 'a' ; ch <= 'z' ; ch++ )
   {
      for ( c = 0 ; c < length ; c++ )
      {
         if ( *pointer == ch )
         {
            *(result+d) = *pointer;
            d++;
         }
         pointer++;
      }
      pointer = s;
   }
   *(result+d) = '\0';

   strcpy(s, result);
   free(result);
}

【问题讨论】:

  • string1 和 string2 会比 string 和 strings 更好的名字

标签: c arrays string compare anagram


【解决方案1】:

您需要使用strcmp()。

另外,您可能需要考虑使用qsort() 或counting sort 代替sort_string()。

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2013-10-26
    • 2016-07-10
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    相关资源
    最近更新 更多