C#程序计算字符串中单词出现的次数
首先设置字符串−
string str = "Hello World! Hello!";
现在检查字符串中单词“Hello”出现的次数并进行循环遍历−
while ((a = str1.IndexOf(pattern, a)) != -1) {
a += pattern.Length;
count++;
}示例
你可以尝试运行以下代码以计算字符串中单词出现的次数。
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;
}
}输出
Occurrence:2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP