C# 程序可统计给定字符串中的单词数
假设我们要统计以下字符串中的单词数 -
str1 = "Hello World!";
现在您需要循环,直到字符串长度并且在找到 “ “ 时增加变量计数,
, \t 如下所示 -
if(str1[a]==' ' || str1[a]=='
' || str1[a]=='\t') { count++; }
您可以尝试运行以下代码,用 C# 统计给定字符串中的单词数。
示例
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);
}
}输出
Total words= 2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP