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

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

เมธอด String.CopyTo() ใน C# ใช้คัดลอกจำนวนตัวอักษรที่ระบุจากตำแหน่งที่กำหนดในสตริงต้นทาง ไปยังตำแหน่งที่กำหนดในอาเรย์ตัวอักษร Unicode (char array)

ไวยากรณ์ (Syntax)

public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
  • sourceIndex — ดัชนีเริ่มต้นในสตริงต้นทาง (zero-based)
  • destination — อาเรย์ char ปลายทางที่จะคัดลอกไป
  • destinationIndex — ดัชนีเริ่มต้นในอาเรย์ปลายทาง
  • count — จำนวนตัวอักษรที่จะคัดลอก

ตัวอย่างที่ 1: คัดลอก 4 ตัวอักษรจากตำแหน่งที่ 1

using System;

public class Demo
{
    public static void Main()
    {
        string str = "JohnAndJacob";
        Console.WriteLine("String = " + str);

        char[] destArr = new char[20];
        str.CopyTo(1, destArr, 0, 4);

        Console.Write(destArr); // แสดงอาเรย์ char ทั้งหมด (มี null chars ต่อท้าย)
    }
}

ผลลัพธ์

String = JohnAndJacob
ohnA

ตัวอย่างที่ 2: คัดลอกทับอาเรย์ที่มีข้อมูลอยู่แล้ว

using System;

public class Demo
{
    public static void Main()
    {
        string str = "JohnAndJacob";
        Console.WriteLine("String = " + str);

        char[] destArr = new char[20];
        destArr[0] = 'A';
        destArr[1] = 'B';
        destArr[2] = 'C';
        destArr[3] = 'D';
        Console.WriteLine("Before: " + new string(destArr)); // ABCD suivi de null chars

        str.CopyTo(2, destArr, 3, 4); // คัดลอก "hnAn" ไปที่ index 3

        Console.WriteLine("After: " + new string(destArr)); // ABC + hnAn + nulls
    }
}

ผลลัพธ์

String = JohnAndJacob
Before: ABCD
After: ABChnAn

สรุป

  • CopyTo() คัดลอก ตัวอักษร (chars) ไปยัง char[] — ไม่คืนค่าสตริงใหม่
  • อาเรย์ปลายทางต้องมีขนาดพอรับข้อมูล (destinationIndex + count ≤ destination.Length) มิฉะนั้นจะโยน ArgumentException
  • ตำแหน่งเริ่มต้น (sourceIndex, destinationIndex) เป็น zero-based
  • ตัวอักษรที่ไม่ได้ถูกคัดลอกในอาเรย์ปลายทางจะคงค่าเดิม (หรือเป็น \0 หากอาเรย์เพิ่งสร้าง)
  • ใช้เมื่อต้องการทำงานกับ char array โดยตรง เช่น interop, low-level string manipulation, performance-critical code

วิธีอื่นที่ใช้บ่อยกว่า

เป้าหมายเมธอดที่แนะนำ
ดึง substringSubstring(startIndex, length) หรือ AsSpan()
แปลงสตริงทั้งหมดเป็น char[]ToCharArray()
แปลง substring เป็น char[]ToCharArray(startIndex, length)
คัดลอกบางส่วนไป char[]CopyTo() (บทความนี้)
เข้าถึง char เดียวstr[index] (indexer)