检查字符串是否是变位词

checking if the string is anagram

这段代码可能有什么问题? 我认为错误出现在我试图将 char 类型转换为 int 的第一个 for 循环中。是否有任何其他方法可用于检查字符串是否为变位词?

# include <stdio.h>
#include <stdlib.h>
# define NO_OF_CHARS 256

void areAnagram(char *str1, char *str2)
{

    int count1[NO_OF_CHARS] = {0};
    int count2[NO_OF_CHARS] = {0};
    int i;


    for (i = 0; str1[i] && str2[i]; i++)
    {
        int a = str1[i] - '0';
        int b = str2[i] - '0'; 
        count1[a]++;
        count2[b]++;
    }


    if (str1[i] || str2[i])
    printf("No");


    for (i = 0; i < NO_OF_CHARS; i++)
        if (count1[i] != count2[i])
            printf("No");

    printf("Yes");
}


int main(void)
{
    char *str1;
    char *str2;
    scanf("%s", str1);
    scanf("%s", str2);
    areAnagram(str1, str2);
    return 0;
}

Gives segmentation fault error at runtime.

PS - 如果 str1 中的所有字符在 str2 中出现的次数相同且 str2 的长度与 str1

相同,则字符串 str1 是 str2 的变位词

您从未为 char *str1;char *str2; 分配任何内存。像这样调整您的代码:

#define MAX_STR_LEN 100

int main(void)
{
    char str1[ MAX_STR_LEN ];
    char str2[ MAX_STR_LEN ];
    scanf("%s", str1);
    scanf("%s", str2);
    areAnagram(str1, str2);
    return 0;
}

您只需要一个计数数组,count。然后将 count 数组元素递增 str1 (count[str1[i]]++;) 并将 count 数组元素递减 str2 (count[str2[i]]--;)。如果 count 的所有元素都为零,则它是变位词。

#include<stdio.h>
#include<conio.h>
void main()
{
    char s[30],s1[30];
    int i,j,count=0,count1=0;
    clrscr();
    printf("enter 2 strings\n");
    gets(s);
    printf("\n");
    gets(s1);
    for(i=0,j=0;s[i]!='[=10=]',s1[j]!='[=10=]';i++,j++)
    {
        count=count+(int)s[i];
        count1=count1+(int)s1[j];
    }
    s[i]='[=10=]';
    printf("\n%d",count);
    printf("\n%d",count1);
    if(count==count1)
    printf(" \n\n string is anagram ");
    else
    printf(" \n\n string is not anagram ");
    getch();

}