C 语言变位词

17 Mar 2025 | 6 分钟阅读

本节将讨论变位词及其程序,以检查给定字符串是否为变位词。一个字符串的变位词是包含相同字符的另一个字符串,只是字符的顺序可能不同。换句话说,变位词是C语言编程的一种技术,用于检查给定字符串是否包含相同数量的字符,只是两个字符串中字符的顺序可以改变。

例如,假设我们有两个字符串:"CAB"和"ABC"。这两个字符串都包含相同的字符,但第一个字符串中字符的排列与第二个字符串不同,这个过程被称为字符串的变位词。

Anagram in C

变位词算法

以下是C语言中变位词的算法:

  1. 从用户输入两个字符串。
  2. 检查每个字符串的长度。如果第一个字符串的长度不等于第二个字符串,则这些字符串不是变位词。
  3. 如果两个字符串的长度相等,则将字符串的字符转换为小写字母,以便更容易进行字符串比较。
  4. 在此之后,使用C库的内置函数对字符串的字符进行排序。如果不存在内置函数,我们将字符串转换为字符数组。
  5. 我们必须将转换后的字符串排序为字符数组。
  6. 最后,我们检查字符串是否相等。

示例1:使用用户定义函数检查字符串变位词的程序

输出

Enter the first string:
pine
Enter the second string
nipe
pine and nipe strings are an anagram of each other.

2nd time run:
Enter the first string:
pine
Enter the second string
nip
pine and nip strings are not an anagram of each other.

示例2:使用嵌套for循环检查字符串变位词的程序

输出

Input the first string: triangle
Input the second string: agtrinle
The first string is an anagram of the second string.

示例3:使用for和if语句检查字符串变位词的程序

输出

Input the first string: SILENCE
Input the second string: LENSICE
The first string is an anagram of the second string.

示例4:对字符串进行排序并检查字符串变位词的程序

输出

Both strings are an anagram of each other.