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

更新時間:23-6 月 2020

625 次瀏覽

開啟您的 職業

透過完成課程認證

開始
廣告
© . All rights reserved.