Home > Backend Development > C++ > What is an anagram in C language?

What is an anagram in C language?

王林
Release: 2023-09-10 08:29:02
forward
1558 people have browsed it

What is an anagram in C language?

变位词字符串实际上是指另一个字符串中出现相同次数的所有字符,我们称之为变位词。

用户输入两个字符串。我们需要计算每个字母('a'到'z')在它们中出现的次数,然后比较它们对应的计数。字母在字符串中出现的频率是它在其中出现的次数。

如果两个字符串具有相同的特定字母频率计数,则可以说这两个字符串是变位词。

示例1

字符串1 - abcd

字符串2 - bdac

这两个字符串具有相同的只出现一次的字母。因此,这两个字符串是变位词。

示例2

字符串1 - programming

字符串2 - gramming

输出 - 这两个字符串不是变位词。

示例

以下是一个变位词的C程序 -

#include <stdio.h>
int check_anagram(char [], char []);
int main(){
   char a[1000], b[1000];
   printf("Enter two strings</p><p>");
   gets(a);
   gets(b);
   if (check_anagram(a, b))
      printf("The strings are anagrams.</p><p>");
   else
      printf("The strings aren&#39;t anagrams.</p><p>");
      return 0;
}
int check_anagram(char a[], char b[]){
   int first[26] = {0}, second[26] = {0}, c=0;
   // Calculating frequency of characters of the first string
   while (a[c] != &#39;\0&#39;) {
      first[a[c]-&#39;a&#39;]++;
      c++;
   }
   c = 0;
   while (b[c] != &#39;\0&#39;) {
      second[b[c]-&#39;a&#39;]++;
      c++;
   }
   // Comparing the frequency of characters
   for (c = 0; c < 26; c++)
   if (first[c] != second[c])
      return 0;
      return 1;
}
Copy after login

输出

执行上述程序时,会产生以下输出 -

Run 1:
Enter two strings
abcdef
deabcf
The strings are anagrams.
Run 2:
Enter two strings
tutorials
Point
The strings aren&#39;t anagrams.
Copy after login

The above is the detailed content of What is an anagram in C language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template