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

Kiểm tra chuỗi chỉ định có trong StringCollection C#

Giới thiệu

Để kiểm tra một chuỗi có tồn tại trong StringCollection hay không, bạn sử dụng phương thức Contains(string). Phương thức trả về true nếu chuỗi được tìm thấy, ngược lại false.

Ví dụ 1: Tìm chuỗi "800" (không tồn tại)

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection stringCol = new StringCollection();
        String[] arr = new String[] { "100", "200", "300", "400", "500" };

        Console.WriteLine("Các phần tử của mảng...");
        foreach (string res in arr)
            Console.WriteLine(res);

        stringCol.AddRange(arr);
        Console.WriteLine("Chuỗi '800' có trong StringCollection không? = " + stringCol.Contains("800"));
    }
}

Kết quả

Các phần tử của mảng...
100
200
300
400
500
Chuỗi '800' có trong StringCollection không? = False

Ví dụ 2: Tìm chuỗi "Katie" (tồn tại)

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection stringCol = new StringCollection();
        String[] arr = new String[] { "John", "Tim", "Kevin", "Bradman", "Katie", "Tom", "Nathan" };

        Console.WriteLine("Các phần tử của mảng chuỗi...");
        foreach (string res in arr)
            Console.WriteLine(res);

        stringCol.AddRange(arr);
        Console.WriteLine("Chuỗi 'Katie' có trong StringCollection không? = " + stringCol.Contains("Katie"));
    }
}

Kết quả

Các phần tử của mảng chuỗi...
John
Tim
Kevin
Bradman
Katie
Tom
Nathan
Chuỗi 'Katie' có trong StringCollection không? = True

Lưu ý: Tìm kiếm phân biệt chữ hoa/thường (case-sensitive). StringCollection sử dụng tìm kiếm tuyến tính O(n).