C# 程式來統計每個字元出現的次數


首先,設定字串 -

string str = "Website";
Console.WriteLine("String: "+str);

檢查字串中的每個字元,並增量變數,該變數將統計該字元出現的次數 -

for (int j = 0; j < str.Length; j++) {
   if (str[0] == str[j]) {
      cal++;
   }
}

示例

您可以嘗試執行以下程式碼來統計每個字元出現的次數。

線上演示

using System;
public class Demo {
   public static void Main() {
      string str = "Website";
      Console.WriteLine("String: "+str);
      while (str.Length > 0) {
         Console.Write(str[0] + " = ");
         int cal = 0;
         for (int j = 0; j < str.Length; j++) {
            if (str[0] == str[j]) {
               cal++;
            }
         }
         Console.WriteLine(cal);
         str = str.Replace(str[0].ToString(), string.Empty);
      }
      Console.ReadLine();
   }
}

輸出

String: Website
W = 1
e = 2
b = 1
s = 1
i = 1
t = 1

更新於: 19-6 月

27K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告