
- 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 the number of words in a string
Let us first declare the string −
string str = "Hello World!";
Now loop through the complete string and find the whitespace or tab or newline character −
while (a <= str.Length - 1) { if(str[a]==' ' || str[a]=='
' || str[a]=='\t') { myWord++; } a++; }
Example
Let us see the complete code to count a number of words in a string in C#.
using System; public class Demo { public static void Main() { int a = 0 , myWord = 1; string str = "Hello World!"; while (a <= str.Length - 1) { if(str[a]==' ' || str[a]=='
' || str[a]=='\t') { myWord++; } a++; } Console.Write("Number of words in the string = {0}
", myWord); } }
Output
Number of words in the string = 2
- Related Articles
- Java Program to count the number of words in a String
- C# program to Count words in a given string
- How to count the number of words in a string in R?
- Java program to count words in a given string
- Python program to Count words in a given string?
- C program to count characters, lines and number of words in a file
- How to count a number of words in given string in JavaScript?
- Count words in a given string in C++
- Program to count number of unique subsequences of a string in C++
- C# Program to count number of Vowels and Consonants in a string
- Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary
- C# program to Reverse words in a string
- Program to count number of palindromes after minimum number of split of the string in C++
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- Python program to count the number of spaces in string

Advertisements