ใน C # String.Contains() เป็นวิธีการสตริง วิธีนี้ใช้เพื่อตรวจสอบว่าสตริงย่อยเกิดขึ้นภายในสตริงที่กำหนดหรือไม่
มันส่งกลับค่าบูลีน หากสตริงย่อยมีอยู่ในสตริงหรือค่าเป็นสตริงว่าง (“”) สตริงย่อยจะส่งกลับ True ไม่เช่นนั้นจะคืนค่าเป็น False
ข้อยกเว้น - วิธีการนี้สามารถให้ ArgumentNullException หาก str เป็นโมฆะ
เมธอดนี้ดำเนินการตรวจสอบตามตัวพิมพ์เล็กและตัวพิมพ์ใหญ่ การค้นหาจะเริ่มต้นจากตำแหน่งอักขระตัวแรกของสตริงเสมอและจะดำเนินต่อไปจนถึงตำแหน่งอักขระสุดท้าย
ตัวอย่างที่ 1
ประกอบด้วยจะพิจารณาตัวพิมพ์เล็กและตัวพิมพ์ใหญ่หากพบว่าสตริงส่งคืนค่าจริงอย่างอื่นเป็นเท็จ
static void Main(string[] args){
string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
if (strs.Contains("sachin")){
System.Console.WriteLine("String Present");
} else {
System.Console.WriteLine("String Not Present");
}
Console.ReadLine();
} ผลลัพธ์
String Not Present
ตัวอย่างที่ 2
static void Main(string[] args){
string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
if (strs.Contains("Sachin")){
System.Console.WriteLine("String Present");
} else {
System.Console.WriteLine("String Not Present");
}
Console.ReadLine();
} ผลลัพธ์
String Present
ตัวอย่างที่ 3
static void Main(string[] args){
string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
var res = strs.Where(x => x == "Sachin").FirstOrDefault();
System.Console.WriteLine(res);
Console.ReadLine();
} ผลลัพธ์
Sachin
ตัวอย่างที่ 4
static void Main(string[] args){
string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
foreach (var item in strs){
if (item == "Sachin"){
System.Console.WriteLine("String is present");
}
}
Console.ReadLine();
} ผลลัพธ์
String is present