
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to Count Words in a Given String
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 “ “,
, \t as shown below −
if(str1[a]==' ' || str1[a]=='
' || 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]=='
' || str1[a]=='\t') { count++; } a++; } Console.Write("Total words= {0}
", count); } }
Output
Total words= 2
Advertisements