String.CopyTo() - คัดลอกตัวอักษรไปยัง Array
คัดลอกกลุ่มตัวอักษรจาก String ต้นทางไปยัง Character Array โดยสามารถระบุตำแหน่งเริ่มต้น จำนวนตัวอักษร และตำแหน่งปลายทางใน Array ได้
Syntax
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
ตัวอย่างการใช้งาน CopyTo()
using System;
class Demo {
static void Main(String[] args) {
string str = "This is it!";
char[] ch = new char[5];
// คัดลอก 2 ตัวอักษร ตั้งแต่ตำแหน่งที่ 2 ไปยัง array ตำแหน่งที่ 0
// "This is it!" -> ตำแหน่ง 2 คือ 'i', ตำแหน่ง 3 คือ 's'
str.CopyTo(2, ch, 0, 2);
Console.WriteLine("Output...");
Console.WriteLine(ch); // ผลลัพธ์: is
}
}
String.Copy() - สร้าง String ใหม่ที่มีเนื้อหาเหมือนกัน
สร้างอ็อบเจ็กต์ String ใหม่ที่มีเนื้อหาเหมือน String ต้นทางอย่างสมบูรณ์
Syntax
public static string Copy(string str)
ตัวอย่างการใช้งาน Copy()
using System;
class Demo {
static void Main(String[] args) {
string str1 = "Welcome!";
string str2 = "user";
// สร้าง String ใหม่จาก str1
str2 = String.Copy(str1);
Console.WriteLine("Output...");
Console.WriteLine(str2); // ผลลัพธ์: Welcome!
}
}
ตารางเปรียบเทียบสรุป
| คุณสมบัติ | String.Copy() | String.CopyTo() |
|---|---|---|
| ประเภทผลลัพธ์ | String (อ็อบเจ็กต์ใหม่) | void (เขียนลง char array ที่มีอยู่แล้ว) |
| พารามิเตอร์ | String ต้นทางเพียงอย่างเดียว | sourceIndex, destination array, destinationIndex, count |
| การจัดการหน่วยความจำ | จัดสรรหน่วยความจำใหม่ | ใช้ Array ที่จัดสรรไว้แล้ว |
| ความยืดหยุ่น | คัดลอกทั้งสตริง | คัดลอกส่วนที่ต้องการได้ (Substring) |
| คืนค่า | String ใหม่ | ไม่คืนค่า (void) |
เมื่อไหร่ควรใช้งานอะไร?
- ใช้ String.Copy() เมื่อต้องการสร้าง String ใหม่อิสระจาก String เดิม
- ใช้ String.CopyTo() เมื่อต้องการนำตัวอักษรบางส่วนไปประมวลผลใน Char Array (เช่น การ Parse, การเข้ารหัส)