

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 occurrences of a word in string
Set the string first −
string str = "Hello World! Hello!";
Now check the string for the occurrences of a word “Hello’ and loop through −
while ((a = str1.IndexOf(pattern, a)) != -1) { a += pattern.Length; count++; }
Example
You can try to run the following code to count occurrences of a word in a string.
using System; class Program { static void Main() { string str = "Hello World! Hello!"; Console.WriteLine("Occurrence:"+Check.CheckOccurrences(str, "Hello")); } } public static class Check { public static int CheckOccurrences(string str1, string pattern) { int count = 0; int a = 0; while ((a = str1.IndexOf(pattern, a)) != -1) { a += pattern.Length; count++; } return count; } }
Output
Occurrence:2
- Related Questions & Answers
- Java program to count occurrences of a word in string
- Python program to count occurrences of a word in a string
- Write a python program to count occurrences of a word in string?
- How to replace all occurrences of a word in a string with another word in java?
- Count occurrences of a character in string in Python
- How to Count Word Occurrences in a Text File using Shell Script?
- Count occurrences of a character in a repeated string in C++
- Python program to count occurrences of an element in a tuple
- How to Count Occurrences of Each Character in String in Android?
- How to count the number of occurrences of a character in a string in JavaScript?
- C# program to count the occurrences of each character
- Java program to count the occurrences of each character
- Count the number of occurrences of a string in a VARCHAR field in MySQL?
- Twice repetitive word count in a string - JavaScript
- Find all occurrences of a word in array in JavaScript
Advertisements