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

已於更新: 2020 年 6 月 19 日

26K+ 瀏覽次數

助力你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.