w3resource

C# Sharp Exercises: Check two strings contain the same character pattern

C# Sharp Regular Expression: Exercise-5 with Solution

Write a C# Sharp program to check whether two given strings contain the same character pattern.

"AACC", "PPQQ" has the same pattern. "FFGG", "ADAD" does not have the same pattern.

Sample Data:
("AACC", "PPRR") -> True
("FFGG", "ADAD") -> False

Sample Solution:

C# Sharp Code:

using System;
using System.Text.RegularExpressions;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            string text1 = "AACC";
            string text2 = "PPRR";
            Console.WriteLine("Original strings: " +text1 +", "+text2);
            if (text1.Length == text2.Length)
            {
                Console.WriteLine("Check said two strings contain the same character pattern: " + test(text1, text2));
            }
            text1 = "FFGG";
            text2 = "ADAD";
            Console.WriteLine("\nOriginal strings: " + text1 + ", " + text2);
            if (text1.Length == text2.Length)
            {
                Console.WriteLine("Check said two strings contain the same character pattern: " + test(text1, text2));
            }
        }

        public static bool test(string text1, string text2)
        {
            for (int i = 0; i < text1.Length; i++)
            {
                if (text1.IndexOf(text1.Substring(i, 1), i + 1) != text2.IndexOf(text2.Substring(i, 1), i + 1))
                    return false;
            }
           return true;
        }
    }
}

Sample Output:

Original strings: AACC, PPRR
Check said two strings contain the same character pattern: True

Original strings: FFGG, ADAD
Check said two strings contain the same character pattern: False

Flowchart:

Flowchart: C# Sharp Exercises - Check two strings contain the same character pattern.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous C# Sharp Exercise: Validate a password.
Next C# Sharp Exercise: C# Sharp Regular Expression Exercises Home.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter