Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอดของสตริง (String Methods) ใน C#

คลาส String มีเมธอดมากมายที่ช่วยให้ทำงานกับออบเจ็กต์สตริงได้สะดวก ตารางด้านล่างแสดงเมธอดที่ใช้บ่อยที่สุด

ลำดับเมธอดและคำอธิบาย
1public static int Compare(string strA, string strB)
เปรียบเทียบออบเจ็กต์สตริงสองตัว และคืนค่าจำนวนเต็มที่บ่งบอกตำแหน่งสัมพัทธ์ในลำดับการจัดเรียง
2public static int Compare(string strA, string strB, bool ignoreCase)
เปรียบเทียบสตริงสองตัว คล้ายเมธอดข้างต้น แต่สามารถละเลยตัวพิมพ์เล็ก/ใหญ่ได้หากพารามิเตอร์ Boolean เป็น true
3public static string Concat(string str0, string str1)
ต่อสตริงสองออบเจ็กต์เข้าด้วยกัน
4public static string Concat(string str0, string str1, string str2)
ต่อสตริงสามออบเจ็กต์เข้าด้วยกัน
5public static string Concat(string str0, string str1, string str2, string str3)
ต่อสตริงสี่ออบเจ็กต์เข้าด้วยกัน
6public bool Contains(string value)
คืนค่าบ่งชี้ว่าออบเจ็กต์ String ที่ระบุมีอยู่ภายในสตริงนี้หรือไม่
7public static string Copy(string str)
สร้างออบเจ็กต์ String ใหม่ที่มีค่าเท่ากับสตริงที่ระบุ
8public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
คัดลอกจำนวนตัวอักษรที่ระบุจากตำแหน่งที่กำหนดของออบเจ็กต์ String ไปยังตำแหน่งที่กำหนดในอาร์เรย์ของตัวอักษร Unicode
9public bool EndsWith(string value)
ตรวจสอบว่าสิ้นสุดของออบเจ็กต์สตริงตรงกับสตริงที่ระบุหรือไม่
10public bool Equals(string value)
ตรวจสอบว่าออบเจ็กต์ String ปัจจุบันและออบเจ็กต์ String ที่ระบุมีค่าเท่ากันหรือไม่
11public 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();
        }
    }
}