让我们首先声明字符串-
string str = "你好,世界!";
现在遍历完整的字符串,找到空白或制表符或换行符-
while (a <= str.Length - 1) { if(str[a]==' ' || str[a]=='\n' || str[a]=='\t') { myWord++; } a++; }
让我们看完整的代码,以计算C#中字符串中的单词数。
using System; public class Demo { public static void Main() { int a = 0 , myWord = 1; string str = "你好,世界!"; while (a <= str.Length - 1) { if(str[a]==' ' || str[a]=='\n' || str[a]=='\t') { myWord++; } a++; } Console.Write("Number of words in the string = {0}\n", myWord); } }
输出结果
Number of words in the string = 2