📜  C#中的StringBuilder.CopyTo方法

📅  最后修改于: 2021-05-29 14:06:55             🧑  作者: Mango

此方法用于将字符从此实例的指定段复制到目标Char数组的指定段。

句法:

参数:

  • sourceIndex :这是从中复制字符的起始位置。索引从零开始。
  • destination :这是要复制字符的数组。
  • destinationIndex :这是目标中要复制字符的起始位置。索引从零开始。
  • count :它是要复制的字符数。

例外情况:

  • ArgumentNullException :如果目的地为null。
  • ArgumentOutOfRangeException :如果sourceIndexdestinationIndexcount小于零,或者sourceIndex大于此实例的长度。
  • ArgumentException :如果sourceIndex + count大于此实例的长度,或者destinationIndex + count大于destination的长度。

范例1:

// C# program to illustrate the
// CopyTo () StringBuilder Method
using System;
using System.Text;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("GeeksForGeeks");
  
        char[] dest = new char[15];
  
        // str index 5 to 5+3 has to
        // copy into Copystring
        // 3 is no. of character
        // 0 is start index of Copystring
        str.CopyTo(5, dest, 0, 3);
  
        // Displaying String
        Console.Write("The Copied String in "+
                        "dest Variable is: ");
        Console.WriteLine(dest);
    }
}
输出:
The Copied String in dest Variable is: For

范例2:

// C# program to illustrate the
// CopyTo() StringBuilder Method
using System;
using System.Text;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str2
            = new StringBuilder("GeeksForGeeks");
  
        char[] dest = { 'H', 'e', 'l', 'l', 'o', ' ',
                           'W', 'o', 'r', 'l', 'd' };
  
        // str index 8 to 8 + 5 has
        // to copy into Copystring
        // 5 is no of character
        // 6 is start index of Copystring
        str2.CopyTo(8, dest, 6, 5);
  
        // Displaying the result
        Console.Write("String Copied in dest is: ");
        Console.WriteLine(dest);
    }
}
输出:
String Copied in dest is: Hello Geeks

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.text.stringbuilder.copyto?view=netframework-4.7.2