คลาส String มีเมธอดมากมายที่ช่วยให้ทำงานกับออบเจ็กต์สตริงได้สะดวก ตารางด้านล่างแสดงเมธอดที่ใช้บ่อยที่สุด
| ลำดับ | เมธอดและคำอธิบาย |
|---|---|
| 1 | public static int Compare(string strA, string strB) เปรียบเทียบออบเจ็กต์สตริงสองตัว และคืนค่าจำนวนเต็มที่บ่งบอกตำแหน่งสัมพัทธ์ในลำดับการจัดเรียง |
| 2 | public static int Compare(string strA, string strB, bool ignoreCase) เปรียบเทียบสตริงสองตัว คล้ายเมธอดข้างต้น แต่สามารถละเลยตัวพิมพ์เล็ก/ใหญ่ได้หากพารามิเตอร์ Boolean เป็น true |
| 3 | public static string Concat(string str0, string str1) ต่อสตริงสองออบเจ็กต์เข้าด้วยกัน |
| 4 | public static string Concat(string str0, string str1, string str2) ต่อสตริงสามออบเจ็กต์เข้าด้วยกัน |
| 5 | public static string Concat(string str0, string str1, string str2, string str3) ต่อสตริงสี่ออบเจ็กต์เข้าด้วยกัน |
| 6 | public bool Contains(string value) คืนค่าบ่งชี้ว่าออบเจ็กต์ String ที่ระบุมีอยู่ภายในสตริงนี้หรือไม่ |
| 7 | public static string Copy(string str) สร้างออบเจ็กต์ String ใหม่ที่มีค่าเท่ากับสตริงที่ระบุ |
| 8 | public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) คัดลอกจำนวนตัวอักษรที่ระบุจากตำแหน่งที่กำหนดของออบเจ็กต์ String ไปยังตำแหน่งที่กำหนดในอาร์เรย์ของตัวอักษร Unicode |
| 9 | public bool EndsWith(string value) ตรวจสอบว่าสิ้นสุดของออบเจ็กต์สตริงตรงกับสตริงที่ระบุหรือไม่ |
| 10 | public bool Equals(string value) ตรวจสอบว่าออบเจ็กต์ String ปัจจุบันและออบเจ็กต์ String ที่ระบุมีค่าเท่ากันหรือไม่ |
| 11 | public static bool Equals(string a, string b) ตรวจสอบว่าออบเจ็กต์ String สองตัวที่ระบุมีค่าเท่ากันหรือไม่ |
ตัวอย่างการใช้เมธอด Contains()
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string str = "This is test";
if (str.Contains("test")) {
Console.WriteLine("Yes, 'test' was found.");
}
Console.ReadKey();
}
}
}