Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chương trình C# kiểm tra chuỗi có toàn ký tự duy nhất (Unique Characters)

Dùng Substring() kiểm tra từng substring ký tự duy nhất. Lặp đến độ dài chuỗi.

Nếu substring nào trùng khớp -> chuỗi KHÔNG có toàn ký tự duy nhất.

Ví dụ

using System;
public class Demo {
    public bool CheckUnique(string str) {
        string one = "", two = "";
        for (int i = 0; i < str.Length; i++) {
            one = str.Substring(i, 1);
            for (int j = 0; j < str.Length; j++) {
                two = str.Substring(j, 1);
                if ((one == two) && (i != j)) return false;
            }
        }
        return true;
    }
    static void Main(string[] args) {
        Demo d = new Demo();
        bool b = d.CheckUnique("amit");
        Console.WriteLine(b);
        Console.ReadKey();
    }
}

Kết quả

True