# count the number of spaces and words in a String

#### jeenal

##### New member
 [h=3]Hi friends,anyone wanted to know the c# string with spaces program in simple way can go through this //C# program to count the number of spaces and words in a String[/h][h=3]using System;[/h][h=3]class SpaceCount[/h][h=3]{[/h][h=3]public static void Main()[/h][h=3]{[/h][h=3]Console.WriteLine("Enter string");[/h][h=3]String str = Console.ReadLine();[/h][h=3][/h][h=3]int cntSp = 0;[/h][h=3]int cntWd = 0;[/h][h=3][/h][h=3]bool fg = false;[/h][h=3]bool fg1 = false;[/h][h=3][/h][h=3]if (str[str.Length - 1] != ' ')[/h][h=3]{[/h][h=3]cntWd++;[/h][h=3]}[/h][h=3]for (int i = 0; i <= str.Length - 1; i++)[/h][h=3]{[/h][h=3]if (str == ' ')[/h][h=3]{[/h][h=3]cntSp++;[/h][h=3]}[/h][h=3][/h][h=3]if (str != ' ')[/h][h=3]{[/h][h=3]fg = true;[/h][h=3]continue;[/h][h=3]}[/h][h=3]else[/h][h=3]fg1 = true;[/h][h=3][/h][h=3]if (fg == true && fg1 == true)[/h][h=3]{[/h][h=3]cntWd++;[/h][h=3]fg = fg1 = false;[/h][h=3]}[/h][h=3]}[/h][h=3]Console.WriteLine("Total number of spaces: " + cntSp);[/h][h=3]Console.WriteLine("Total number of words: " + (cntWd));[/h][h=3]}[/h][h=3]}[/h]

[TR]
[TD][h=3]Output

Enter string
[/h][h=3]This is C#[/h][h=3]Total number of spaces: 2[/h][h=3]Total number of words: 3[/h][/TD]
[TD][h=3][/h][/TD]
[/TR]

As i am a beginner i got to know the simple and with easy solutions to learn c++,c,c# programs with online compiler from online free tutorials on cbtsam.com you people can also try this out.

Last edited:

Replies
8
Views
628
Replies
3
Views
268
Replies
2
Views
429
Replies
1
Views
659
Replies
3
Views
945