#include <stdio.h>
main()
{
char *a = "stack";
char *b = "cats";
int l = 0; // for length of string b
clrscr();
while (*b != NULL)
{
l++;
b++;
}
b--; // now b points to last char of the string
// printf("%d\n", l);
while ((*a - *b == 32) || (*a == *b))
{
printf("%c %c\n", *a, *b);
a++;
b--;
l--;
if (l == 0)
break;
}
l == 0 ? printf("anagrams") : printf("not anagrams");
getch();
}
我编写了代码来检查两个字符串 a 和 b 是否是变位词。
当b 比a 短 并且是a 的子字符串时,代码显示误报。
例如。 b 是 “cats”,反过来是 “stac”,a 是 “stack” 代码将 a 和 b 显示为变位词
最佳答案
一些伪代码用于检查两个字符串是否是彼此的变位词(使用您的变量名):
if (strlen(a) != strlen(b))
// Not an anagram
return
char *a_sorted = sort_chars(a)
char *b_sorted = sort_chars(b)
// Once the characters in each word are re-arranged in alphabetical
// order, we can just test for equality. Anagrams will be equal
// (Note that this will not work on multi-word strings with differing
// numbers of whitespace characters)
if (strcmp(a_sorted, b_sorted) == 0)
// Anagram!
else
// Not an anagram
这里真正的工作是在 sort_chars(in)
函数中,它按字母顺序对 in
字符串中的字符进行排序,并返回一个指向包含排序的字符。使用字符的数字 ASCII 值(它们已经按字母顺序排列,是的,有人正在做某事!),类似于 bubble sort (或您要使用的任何其他排序算法)应该可以正常工作。
关于c - 如何更正此代码以检查字谜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44212095/