w3resource

C#: Count the number of times the string 'aa' appears in a given string and assume that 'aaa' contains two 'aa'


Count 'aa' in String

Write a C# Sharp program to count the number of times the string "aa" appears in a given string and assume that "aaa" contains two "aa".

Visual Presentation:

C# Sharp: Basic Algorithm Exercises -  Count the string 'aa' in a given string and assume 'aaa' contains two 'aa'.

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("bbaaccaag"));  // Output: 2
            Console.WriteLine(test("jjkiaaasew"));  // Output: 1
            Console.WriteLine(test("JSaaakoiaa"));  // Output: 2
            Console.ReadLine();  // Keeping the console window open
        }

        // Method to count the occurrences of the substring "aa" in the given string 's'
        public static int test(string s)
        {
            int ctr_aa = 0;  // Counter to store the number of occurrences of "aa" in the string

            // Loop through the string characters up to the second-to-last character
            for (int i = 0; i < s.Length - 1; i++)
            {
                // Check if the current and next character form the substring "aa"
                if (s.Substring(i, 2) == "aa")
                {
                    ctr_aa++;  // Increment the counter if "aa" is found
                }
            }

            return ctr_aa;  // Return the total count of occurrences of "aa" in the given string
        }
    }
}

Sample Output:

2
2
3

Flowchart:

C# Sharp: Flowchart: Count the string "aa" in a given string and assume 'aaa' contains two 'aa'.

For more Practice: Solve these Related Problems:

  • Write a C# program to count the number of overlapping "aa" patterns in a string.
  • Write a C# program to count how many "aa" pairs are surrounded by digits in a given string.
  • Write a C# program to count instances of "aa" where the second 'a' is not the last character in the string.
  • Write a C# program to count all "aa" patterns that are not part of an "aaa" pattern.

Go to:


PREV : n Copies of First Three Characters.
NEXT : First 'a' Followed by Another 'a'.

C# Sharp Code Editor:



Improve this sample solution and post your code through Disqus

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.