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-Jun-2020

6K+ 瀏覽

開啟你的 職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.