Interview Question Categories

FIND GIVEN PATTERN AND REPLACE IT WITH GIVEN STRING

FIND GIVEN PATTERN AND REPLACE IT WITH GIVEN STRING


namespace FindGivenPatternAndReplaceWitStr
{
    //Implementation of finding all the occurrence of the given pattern in given String
    //and then replacing it with some other given string
    class Program
    {
        public static String FindAndReplace(String GivenString, String Pattern, String ReplaceString)
        {
            int j = 0;
            int tempi;

            for (int i = 0; i < GivenString.Length; i++)
            {
                tempi = i;
                j = 0;
                while (i<GivenString.Length && j< Pattern.Length && GivenString[i] == Pattern[j])
                {
                    i++;
                    j++;
                }
                if (j == Pattern.Length)
                {
                    GivenString = GivenString.Substring(0, tempi) + ReplaceString + GivenString.Substring(i, GivenString.Length - i);
                    i = tempi + ReplaceString.Length-1;
                    
                    continue; 
                }
                i = tempi;
            }
            return GivenString;
        }


        static void Main(string[] args)
        {
            String GivenString = "fasdasdkfhawhasdrhasdfasdbygyasgfadfsdkfwerhasdfhpraasd";
            String Pattern = "asd";
            String ReplaceString = ",";
            int tempi;
            int i = 0;
            int j;

            while(i<GivenString.Length)
            {
                tempi = i;
                j = 0;
                while (i < GivenString.Length && j < Pattern.Length && GivenString[i] == Pattern[j])
                {
                    i++;
                    j++;
                }
                if (j == Pattern.Length)
                {
                    GivenString = GivenString.Substring(0, tempi) + ReplaceString + GivenString.Substring(i, GivenString.Length - i);
                    i = tempi + ReplaceString.Length;
                    continue;
                }
                j = 0;
                i = tempi+1;    
            }
            Console.WriteLine(GivenString);
            GivenString = "fasdasdkfhawhasdrhasdfasdbygyasgfadfsdkfwerhasdfhpraasd";
            Console.WriteLine(FindAndReplace(GivenString, Pattern, ReplaceString));
        }
    }
}

No comments:

Post a Comment