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:
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 :
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.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework