Javatpoint Logo
Javatpoint Logo

Anagram in C

This section will discuss the anagram and its program to check whether the given string is the Anagram or not. An anagram of a string is a string that contains the same characters in both the strings, except the order of characters can be different in the strings. In other words, anagrams are a technique of C programming that checks whether a given string contains the same number of characters, except that the sequence of characters can be changed in both strings.

For example, suppose we have two strings: "CAB" and "ABC". Both contain the same characters in these strings, but the arrangements of the first strings' characters are different from the second strings, and the process is termed the anagram of strings.

Anagram in C

Algorithm of the Anagram string

Following are the algorithms of the anagram string in C, as follows:

  1. Input two strings from the user.
  2. Check the length of each string. If the length of the first string is not equal to the second string, the strings are not an anagram.
  3. If the length of both strings is equal, convert the string's characters into lower case letters that make the comparison of the string easier.
  4. After this, sort the characters of the strings using the built-in function of the C library to sort the strings. And if there is no built-in function, we convert the string to a character array.
  5. We must sort the converted string into a character array.
  6. And last, we check for the equality of the strings.

Example 1: Program to check the anagram of the string using user-defined function

Output

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.

Example 2: Program to check the anagram of the string using nested for loop

Output

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

Example 3: Program to check the anagram of the string using the for and if statement

Output

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

Example 4: Program to sort the string and check the anagram of the strings

Output

Both strings are an anagram of each other.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA