w3resource

C#: Check whether a given string contain the character 'z' from 2 to 4 times


Contains 2-4 'z' Characters

Write a C# Sharp program to check if a given string contains between 2 and 4 'z' characters.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Check if a given string contains between 2 and 4 'z' character.

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 strings
            Console.WriteLine(test("frizz")); // Output: True
            Console.WriteLine(test("zane"));  // Output: True
            Console.WriteLine(test("Zazz"));  // Output: False
            Console.WriteLine(test("false")); // Output: False
            Console.WriteLine(test("zzzz"));  // Output: True
            Console.WriteLine(test("ZZZZ"));  // Output: False
            Console.ReadLine();              // Keeping the console window open
        }

        // Method to check if the input string contains 'z' from 2 to 4 times
        public static bool test(string str)
        {
            int ctr = 0; // Counter to store the number of occurrences of 'z'

            // Loop through each character in the input string
            for (int i = 0; i < str.Length; i++)
            {
                // Check if the current character is 'z'
                if (str[i] == 'z')
                {
                    ctr++; // Increment the counter if the character is 'z'
                }
            }

            // Return true if the count of 'z' is greater than 1 and less than or equal to 4, otherwise return false
            return ctr > 1 && ctr <= 4;
        }
    }
}

Sample Output:

True
False
True
False
True
False

Flowchart:

C# Sharp: Flowchart: Check if a given string contains between 2 and 4 'z' character).

For more Practice: Solve these Related Problems:

  • Write a C# program to check if a given string contains exactly 3 'z' or 'Z' characters, case-insensitively.
  • Write a C# program to count the number of 'z' characters and return true if the count is a prime number between 2 and 7.
  • Write a C# program that returns true if the number of 'z' characters is within 2 to 4 and the total string length is at least 6.
  • Write a C# program to check whether a given string contains at least one pair of consecutive 'z' characters and no more than four total.

Go to:


PREV : Largest in Range 20-30.
NEXT : Same Last Digit for Two Integers.

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.