Given two strings, check if the anagram of one string is present in the other

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "bat";
            string str2 = "tablet";
            int flag = 0;
            for (int i = 0; i <= str2.Length - str1.Length; i++)
            {
                if(IsAnagram(str1, str2.Substring(i, str1.Length)))
                {
                    flag = 1;
                    Console.WriteLine("Anagram of one string is present in the other");
                    Console.WriteLine(str1);
                    Console.WriteLine(str2.Substring(i, str1.Length));
                    break;
                }
            }
            if (flag == 0)
            {
                Console.WriteLine("Anagram of one string is not present in the other");
            }
        }

        public static bool IsAnagram(string str1, string str2)
        {
            if (str1 == null || str2 == null || str1.Length != str2.Length)
            {
                return false;
            }
            else
            {
                if (GetSortedCharString(str1) == GetSortedCharString(str2))
                {
                    return true;
                }
            }
            return false;
        }

        public static string GetSortedCharString(string str)
        {
            char[] chArray = str.ToCharArray();
            Array.Sort<char>(chArray);
            return (new string(chArray));
        }
    }
}

Output
=======
Anagram of one string is present in the other
bat
tab
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s