此方法用於將字符從此實例的指定段複製到目標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
參考:
- https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.copyto?view=netframework-4.7.2
相關用法
- C# Random.Next()用法及代碼示例
- C# Uri.FromHex()用法及代碼示例
- C# Uri.IsHexDigit()用法及代碼示例
- C# Uri.IsBaseOf(Uri)用法及代碼示例
- C# Math.Log()用法及代碼示例
- C# Queue.Contains()用法及代碼示例
- C# Uri.GetHashCode()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 StringBuilder.CopyTo Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。