C# 程式用於統計字串中的單詞數


首先,讓我們宣告字串-

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

更新於: 19-6-2020

6 千+ 次瀏覽

開啟您的職業

填寫課程認證

開始
廣告
© . All rights reserved.