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
廣告