C# 程序用于计算字符串中的单词数
csharpserver side programmingprogramming更新于 2025/9/24 13:30:00
首先我们声明字符串 −
string str = "Hello World!";
现在循环遍历整个字符串并找到空格或制表符或换行符 −
while (a <= str.Length - 1) {
if(str[a]==' ' || str[a]=='
' || str[a]=='\t') {
myWord++;
}
a++;
}
示例
让我们看一下在 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);
}
}
输出
Number of words in the string = 2

