C program to find all anagrams in a string?

devquora
devquora

Posted On: Mar 07, 2022

 

Anagram strings are those strings which have same letters but in different orders. Method to check: First, sort the strings and then compare the sorted strings. If strings are equal then they are anagram strings otherwise not.

Program:

#include <stdio.h>
#include <string.h>
int main () { 
  char str1[] = "listen";   
char str2[] = "silent";
char temp;  
 int i, j;  
 int n1  = strlen(str1);  
 int n2 = strlen(str2);  
 //strings are not anagrams if they are of different length
  if( n1 != n2) {    
printf("%s and %s are not anagrams! \n", str1, str2);   
return 0; } 
for(i=0; i<n1-1; i++) {  // first sort both strings 
for (j = i+1; j < n1; j++) {     
if (str1[i] > str1[j]) {            
temp= str1[i];           
str1[i] = str1[j];       
str1[j] = temp;         }       
if (str2[i] > str2[j]) {  
temp  = str2[i];        
str2[i] = str2[j];           
str2[j] = temp;         }
}   }  
for(i = 0; i<n1; i++) {  // Compare character by character both strings
if(str1[i] != str2[i]) {         
printf("Strings are not anagrams \n", str1, str2);         
return 0;      
}}   
printf("Strings are anagrams! \n");   return 0;}

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Amazon Interview Questions

    Write a program to reverse a string without using Library Function?

    There is&nbsp;a number&nbsp;of ways to reverse a string in programming. Here we going to see how to reverse a string in C language. Note: Below programs are written in C language. It takes a string a...