ใช้เมธอด Contains() ตรวจสอบว่าสตริงมี substring ที่ต้องการหรือไม่
string str1 = "United"; string str2 = "Uni"; bool result = str1.Contains(str2); // true
ตัวอย่างโค้ดเต็ม
using System;
public class Demo {
public static void Main() {
string str1 = "United", str2 = "Uni";
bool 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
เมธอดที่เกี่ยวข้อง:
StartsWith()- ตรวจสอบขึ้นต้นด้วยEndsWith()- ตรวจสอบลงท้ายด้วยIndexOf()- หาตำแหน่ง (คืน -1 ถ้าไม่เจอ)