Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sao chép chuỗi (String) sang chuỗi khác trong C#

Để sao chép một chuỗi sang chuỗi khác trong C#, ta dùng phương thức tĩnh String.Copy. Dưới đây là các ví dụ.

Ví dụ 1

using System;

public class Demo {
    static public void Main(){
        string str1 = "Kevin";
        string str2 = String.Copy(str1);
        
        Console.WriteLine("String1 = " + str1);
        Console.WriteLine("String2 = " + str2);
    }
}

Kết quả

String1 = Kevin
String2 = Kevin

Ví dụ 2

using System;

public class Demo {
    static public void Main(){
        string str1 = "Maisie";
        string str2 = "Ryan";
        
        Console.WriteLine("String1 (Before copying) = " + str1);
        Console.WriteLine("String2 (Before copying) = " + str2);
        
        str2 = String.Copy(str1);
        
        Console.WriteLine("String1 = " + str1);
        Console.WriteLine("String2 (Updated) = " + str2);
    }
}

Kết quả

String1 (Before copying) = Maisie
String2 (Before copying) = Ryan
String1 = Maisie
String2 (Updated) = Maisie