w3resource

C#: Function to count number of spaces in a string

C# Sharp Function: Exercise-4 with Solution

Write a program in C# Sharp to create a function to input a string and count the number of spaces within the string.

Visual Presentation:

C# Sharp Exercises: Function: Function to count number of spaces in a string

Sample Solution:

C# Sharp Code:

using System;

// Define a public class named 'funcexer4'
public class funcexer4
{
    // Define a public static method 'SpaceCount' that counts spaces in a string and returns the count
    public static int SpaceCount(string str)
    {   
        // Initialize a counter for spaces
        int spcctr = 0;
        string str1;

        // Loop through each character in the string
        for (int i = 0; i < str.Length; i++)
        {
            // Extract each character individually
            str1 = str.Substring(i, 1);

            // Check if the character is a space, if true, increment the space counter
            if (str1 == " ")
                spcctr++;
        }

        return spcctr; // Return the total count of spaces in the string
    }

    // Main method, the entry point of the program
    public static void Main()
    {
        string str2;

        // Print a description of the program
        Console.Write("\n\nFunction to count number of spaces in a string :\n");
        Console.Write("----------------------------------------------------\n");

        // Prompt the user to input a string and read the input
        Console.Write("Please input a string : ");
        str2 = Console.ReadLine();

        // Call the 'SpaceCount' method and print the count of spaces in the input string
        Console.WriteLine("\"" + str2 + "\"" + " contains {0} spaces", SpaceCount(str2));
    }    
}

Sample Output:

Function to count number of spaces in a string :                       
----------------------------------------------------                   
Please input a string : w3resource is a tutorial                       
"w3resource is a tutorial" contains 3 spaces

Flowchart :

Flowchart: C# Sharp Exercises - Function to count number of spaces in a string

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to create a function for the sum of two numbers.
Next: Write a program in C# Sharp to calculate the sum of elements in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/function/csharp-function-exercise-4.php