ใช้เมธอด contain() ใน C# เพื่อตรวจสอบว่าสตริงย่อยอยู่ในสตริงที่กำหนดหรือไม่
สมมุติว่าสตริงคือ −
United
ภายในสตริง คุณต้องค้นหาสตริงย่อย "Uni" ในการนั้น ให้ใช้วิธีการที่มีและใช้มันเหมือนตัวอย่างโค้ดต่อไปนี้ -
res = str1.Contains(str2);
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อค้นหาสตริงย่อยในสตริง
using System;
public class Demo {
public static void Main() {
string str1 = "United", str2 = "Uni";
bool res;
res = str1.Contains(str2);
if (res)
Console.Write("The substring " + str2 + " is in the string " + str1);
else
Console.Write("The substring " + str2 + " is not in the string " + str1);
}
} ผลลัพธ์
The substring Uni is in the string United