📌  相关文章
📜  C#|如何将一个字符串复制到另一个字符串

📅  最后修改于: 2021-05-29 20:12:50             🧑  作者: Mango

String.Copy(String)方法用于创建具有与指定String相同值的String的新实例。换句话说,此方法用于将一个字符串的数据复制到新的字符串。
新字符串包含与原始字符串相同的数据,但表示不同的对象引用。

句法:

public static string Copy (string value);

参数:此处的是要复制的字符串。

返回值:该方法的返回类型为System.String 。此方法返回一个新字符串,其中包含与value相似的数据。

异常:如果该值为null,则此方法将提供ArgumentNullException。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# program to illustrate Copy() Method
using System;
   
class GFG {
   
    // Main Method
    static public void Main()
    {
   
        // string which is to be copied
        string strA = "GeeksforGeeks";
   
        // Copy the data of strA string
        // into strB string
        // using Copy() method
        string strB = String.Copy(strA);
          
        Console.WriteLine("Original String strA: {0}", strA);
        Console.WriteLine("Copied String strB: {0}", strB);
    }
}
输出:
Original String strA: GeeksforGeeks
Copied String strB: GeeksforGeeks

范例2:

// C# program to check reference of strings
using System;
  
class GFG {
      
    // Main Method
    static public void Main()
    {
  
        // string
        string strA = "GeeksforGeeks";
        string strB = "C# Tutorials";
        Console.WriteLine("Original string A: {0}", strA);
        Console.WriteLine("Original string B: {0}", strB);
        Console.WriteLine();
  
        Console.WriteLine("After copy:");
  
        // copy the data of strA string 
        // into strB string
        // using Copy() method
        strB = String.Copy(strA);
          
        Console.WriteLine("Value of string A: {0}", strA);
        Console.WriteLine("Value of string B: {0}", strB);
  
        // Checking the reference of both string
        Console.WriteLine("Is reference of strings is equal : {0}",
                               Object.ReferenceEquals(strA, strB));
    }
}
输出:
Original string A: GeeksforGeeks
Original string B: C# Tutorials

After copy:
Value of string A: GeeksforGeeks
Value of string B: GeeksforGeeks
Is reference of strings is equal : False

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system。字符串.copy?view = netframework-4.7.2#definition