w3resource

C#: Count a substring of length 2 appears any where in a given string as well as appears at the end of the string


C# Sharp Basic Algorithm: Exercise-31 with Solution

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

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Count a substring of length 2 appears in a given string and also as the last 2 characters of the string.

Sample Solution:-

C# Sharp Code:

using System;

// Namespace declaration
namespace exercises
{
    // Class declaration
    class Program
    {
        // Main method - entry point of the program
        static void Main(string[] args)
        {
            // Displaying the output of the 'test' method with different string inputs
            Console.WriteLine(test("abcdsab"));    // Output: 2
            Console.WriteLine(test("abcdabab"));   // Output: 3
            Console.WriteLine(test("abcabdabab")); // Output: 4
            Console.WriteLine(test("abcabd"));     // Output: 0
            Console.ReadLine(); // Keeping the console window open
        }

        // Method to count occurrences of the last two characters in substrings
        public static int test(string str)
        {
            var last_two_char = str.Substring(str.Length - 2); // Getting the last two characters of the input string
            var ctr = 0; // Counter to store the number of occurrences

            // Loop through the string except for the last two characters
            for (var i = 0; i < str.Length - 2; i++)
            {
                // Check if the substring of length 2 starting from index 'i' matches the last two characters
                if (str.Substring(i, 2).Equals(last_two_char))
                {
                    ctr++; // Increment the counter if the condition is met
                }
            }

            return ctr; // Return the count of occurrences
        }
    }
}

Sample Output:

1
2
3
0

Flowchart:

C# Sharp: Flowchart: Count a substring of length 2 appears in a given string and also as the last 2 characters of the string.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to create a string like  "aababcabcd" from a given string "abcd".
Next: Write a C# Sharp program to check a specified number is preset in a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.