Đầu tiên, đặt chuỗi -
string str = "Website";
Console.WriteLine("String: "+str); Kiểm tra mọi ký tự trong chuỗi và tăng một biến sẽ đếm số lần xuất hiện của ký tự đó -
for (int j = 0; j < str.Length; j++) {
if (str[0] == str[j]) {
cal++;
}
} Ví dụ
Bạn có thể thử chạy đoạn mã sau để đếm số lần xuất hiện của mỗi ký tự.
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();
}
} Đầu ra
String: Website W = 1 e = 2 b = 1 s = 1 i = 1 t = 1