DEV Community

221910307028
221910307028

Posted on • Edited on

1

How to Know if two given strings are anagrams in C

What is an Anagram?

An anagram is a word made by rearranging an original word’s letters to make a new word.

For example, “listen” and “silent” are anagrams of each other because we can create them by rearranging the other’s letters. In other words, the strings contain the same letters, but in a different order.

Code

We are using the sorting method in the C program below to figure out if two strings are anagrams:

      #include <stdio.h>
      #include <string.h>

      void main () 
      {
         char s1[] = "listen";
         char s2[] = "silent";
         char t;
         int i, j;
         int n  = strlen(s1);
         int n1 = strlen(s2);

         // If both strings are of different length, then we can directly say they are not anagrams
         if( n != n1) 
         {    
            printf("%s and %s are not anagrams! \n", s1, s2);
         }

         // Soring both strings −

          for (i = 0; i < n-1; i++) 
         {
            for (j = i+1; j < n; j++) 
            {
               if (s1[i] > s1[j]) 
               {
                  t = s1[i];
                  s1[i] = s1[j];
                  s1[j] = t;
               }
               if (s2[i] > s2[j]) 
               {
                  t = s2[i];
                  s2[i] = s2[j];
                  s2[j] = t;
               }
           }
        }

         // Compare both strings character by character

          for(i = 0; i<n; i++) 
         {
            if(s1[i] != s2[i]) 
            {    
               printf("Given strings are not anagrams\n");
            }
         }
         printf("Given strings are anagrams!\n");
      }
Enter fullscreen mode Exit fullscreen mode

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay