Write a C# Sharp program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string. Do not count the end substring


Write a C# Sharp program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string. Do not count the end substring

Sample Output:

1
2
3
0

 

الأجوبة

ابحث عن مسائل برمجة سي شارب | c# programming بالانجليزي

using System;
namespace exercises
{
   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(test("abcdsab"));
            Console.WriteLine(test("abcdabab"));
            Console.WriteLine(test("abcabdabab"));
            Console.WriteLine(test("abcabd"));
            Console.ReadLine();
        }
        public static int test(string str)
        {
            var last_two_char = str.Substring(str.Length-2);
            var ctr = 0;

            for (var i = 0; i < str.Length-2; i++)
            {
               if (str.Substring(i, 2).Equals(last_two_char)) ctr++;
            }
            return ctr;
        }
   }
}

محتاج مساعدة؟ تواصل مع مدرس اونلاين الان!