我正在检查字符串字谜。但我无法理解背后的逻辑
int check_anagram(char a[], char b[])
功能。
此代码仅给出小写或大写字符串字谜。 我想让它不区分大小写。请提供必要的更改。
#include<stdio.h>
#include<conio.h>
#include<string.h>
int check_anagram(char [], char []);
int main()
{
char a[100], b[100];
int flag;
printf("Enter first string\n");
gets(a);
printf("Enter second string\n");
gets(b);
flag = check_anagram(a, b);
if (flag == 1)
printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
else
printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
system("pause");
return 0;
}
int check_anagram(char a[], char b[])
{
int first[26] = {0}, second[26] = {0}, c = 0;
while (a[c] != '\0')
{
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '\0')
{
second[b[c]-'a']++;
c++;
}
for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}
return 1;
}
请解释一下:
-
first[a[c]-'a']++;
-
second[b[c]-'a']++;
最佳答案
first[a[c]-'a']++;
正在获取字符串“a”的第 c 个字母的字母索引 (0-26)。例如,如果我们输入“test”,那么对于每个字母,a[c] 等于:
“t”、“e”、“s”、“t”
然后 a[c] - 'a' 等于(其中 'a' == 97 且 't' == 116):
19、4、18、19
然后,first[a[c] - 'a']++ 递增每个字符的字母索引 a,因此 first 的结果如下:
a e s t
{0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0}
为了使您的代码正常工作,您只需预先格式化每个字符串,使其均为小写,或者检查大写字符并添加 32(ascii 差异)。看一张ascii表可以帮助你,这里有一个:ASCII TABLE - IMAGE
关于c - 下面的C函数是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19947795/