
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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
- Related Articles
- Java program to count words in a given string
- Python program to Count words in a given string?
- Count words in a given string in C++
- How to count a number of words in given string in JavaScript?
- Java Program to count the number of words in a String
- C# program to count the number of words in a string
- Python program to count words in a sentence
- Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary
- C# program to Reverse words in a string
- Count words in a sentence in Python program
- Reverse words in a given String in Java
- Reverse words in a given String in Python
- Reverse words in a given String in C#
- How to count the number of words in a string in R?
- Python program to count number of vowels using set in a given string

Advertisements