Let’s say we want to count the number of words in the following string −
str1 = "Hello World!";
Now you need to loop though till string length and increment the variable count on finding “ “, \n, \t as shown below −
if(str1[a]==' ' || str1[a]=='\n' || str1[a]=='\t') {
count++;
}You can try to run the following code to count words in a given string in C#.
Example
using System;
public class Demo {
public static void Main() {
string str1;
int a, count;
str1 = "Hello World!";
a = 0;
count = 1;
while (a <= str1.Length - 1) {
if(str1[a]==' ' || str1[a]=='\n' || str1[a]=='\t') {
count++;
}
a++;
}
Console.Write("Total words= {0}\n", count);
}
}Output
Total words= 2