Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c - Sorting Strings Using qsort to Check If They Are Anagram

static int myCompare (const void * a, const void * b)
{
    return strcmp (*(const char **) a, *(const char **) b);
}

void sort1(const char *str1[],int n1)
{
    qsort (str1,n1,sizeof (const char *), myCompare);

}
void sort2(const char *str2[], int n2)
{
    qsort( str2, n2, sizeof (const char *),myCompare);
}

int main ()
{
    const char *str1[] = {"listen"};
    const char *str2[] = {"silent"};

    int n1 = sizeof(str1)/sizeof(str1[0]);
    int n2 = sizeof(str2)/sizeof(str2[0]);

    sort1(str1,n1);
    sort2(str2,n2);

    int x = strcmp(*str1,*str2);

    if(x==0) 
     printf("
 Both The Strings Are Anagram
");

    else
    printf("
 Strings Are Not Anagram 
"); 
    return 0;
}

I wish to sort the strings and then compare them, to check if they are Anagram.

The Problem is Strings do not get sorted.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If what you need is to check if two strings are anagrams by sorting them, you could place the strings in single dimensional character arrays like

char str1[]="silent";
char str2[]="listen";

qsort(str1, strlen(str1), sizeof(str1[0]), cmp);
qsort(str2, strlen(str2), sizeof(str2[0]), cmp);

where cmp() is a function

int cmp(const void *a, const void *b)
{
    return *(const char *)a - *(const char *)b;
}

After the qsort() calls, use strcmp() like

if(strcmp(str1, str2)==0)
{
    //anagrams
}

Read about qsort() here and here.


Note that in

const char *str1[] = {"listen"};

the string cannot be modified and likewise in the case of

char *str1[]={"listen"};

only in this case, you might get a run-time error as it is a string literal. See this post.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...