w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Function: 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 number of spaces are in the string.

Pictorial Presentation:

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

Sample Solution:

C# Sharp Code:

using System;
public class funcexer4
{
	public static int SpaceCount(string str)
	{   
		int spcctr=0;
		string str1;
		for (int i = 0;i < str.Length;i++)
			{
			  str1 = str.Substring(i,1);
			  if (str1 == " ")
					spcctr++;
			}
		return spcctr;
	}
public static void Main()
	{
	    string str2;
		Console.Write("\n\nFunction to count number of spaces in a string :\n");
        Console.Write("----------------------------------------------------\n");
		Console.Write("Please input a string : ");
        str2 = Console.ReadLine();
		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?



New Content: Composer: Dependency manager for PHP, R Programming