当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# StringBuilder.CopyTo用法及代码示例


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

用法:

public void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count);



参数:

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

异常:

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

示例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

参考:



相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 StringBuilder.CopyTo Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。