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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP