Giới thiệu
Phương thức Contains(string value) của lớp String kiểm tra xem chuỗi hiện tại có chứa chuỗi con value hay không. Trả về true nếu tìm thấy, false nếu không. Tìm kiếm phân biệt chữ hoa/chữ thường (case-sensitive) và dùng so sánh ordinal (binary).
Cú pháp
public bool Contains(string value); // .NET Core 2.0+ có overload: public bool Contains(string value, StringComparison comparisonType);
Ví dụ 1
using System;
public class Demo
{
public static void Main(string[] args)
{
string str1 = "Akon";
string str2 = "Ak";
Console.WriteLine("String 1 = " + str1);
Console.WriteLine("HashCode của String 1 = " + str1.GetHashCode());
Console.WriteLine("String 2 = " + str2);
Console.WriteLine("HashCode của String 2 = " + str2.GetHashCode());
Console.WriteLine("String 1 bằng String 2: {0}", str1.Equals(str2));
Console.WriteLine("String 1 có chứa String 2? = " + str1.Contains(str2));
}
}
Kết quả
String 1 = Akon HashCode của String 1 = 416613838 String 2 = Ak HashCode của String 2 = -839927841 String 1 bằng String 2: False String 1 có chứa String 2? = True
Ví dụ 2
using System;
public class Demo
{
public static void Main(string[] args)
{
string str1 = "Jacob";
string str2 = "John";
Console.WriteLine("String 1 = " + str1);
Console.WriteLine("HashCode của String 1 = " + str1.GetHashCode());
Console.WriteLine("String 2 = " + str2);
Console.WriteLine("HashCode của String 2 = " + str2.GetHashCode());
bool res = str1.Contains(str2);
if (res)
Console.WriteLine("Tìm thấy!");
else
Console.WriteLine("Không tìm thấy!");
}
}
Kết quả
String 1 = Jacob HashCode của String 1 = -790718923 String 2 = John HashCode của String 2 = -1505962600 Không tìm thấy!
Overload với StringComparison (.NET Core 2.0+ / .NET Standard 2.1+)
string text = "Thİs is a Test"; // Có 'İ' (I có chấm - Turkish)
Console.WriteLine(text.Contains("this")); // False (case-sensitive ordinal)
Console.WriteLine(text.Contains("this", StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(text.Contains("this", StringComparison.CurrentCultureIgnoreCase)); // True (trừ Turkish)
Console.WriteLine(text.Contains("this", StringComparison.InvariantCultureIgnoreCase)); // True
Lưu ý quan trọng
Contains()mặc định dùngStringComparison.Ordinal(so sánh binary, case-sensitive).- Để không phân biệt hoa/thường: dùng overload
Contains(value, StringComparison.OrdinalIgnoreCase). - Ném
ArgumentNullExceptionnếuvaluelà null. - Chuỗi rỗng (
"") luôn được coi là chứa trong bất kỳ chuỗi nào (trả về true). - Hiệu suất: O(n*m) naive, nhưng .NET tối ưu hóa (Boyer-Moore cho pattern dài).
- Để tìm tất cả vị trí: dùng
IndexOftrong vòng lặp hoặc Regex.