C#的String.CopyTo()方法示例
C#方法String.CopyTo()
String.CopyTo()方法用于将指定数量的字符从字符串的给定索引复制到字符数组中的指定位置。
语法:
public void CopyTo (int source_index,
char[] destination,
int destination_index,
int count);参数:
source_index-要从中复制字符串的字符串的索引
destination-您要在其中复制字符串部分的目标字符数组
destination_index-目标字符数组中的索引
count-要在字符数组中复制的字符总数
返回值:void-不返回任何内容。
示例
Input:
string str = "Hello world!";
char[] arr = { 'I', 'n', 'c', 'l', 'u', 'd', 'H', 'e', 'l', 'p' };
copying "Hello " to arr:
str.CopyTo(0, arr, 0, 6);
Output:
str = Hello world!
arr = Hello HelpC#使用String.CopyTo()方法将字符从字符串复制到字符数组的示例
using System;
using System.Text;
namespace Test
{
class Program
{
static void printCharArray(char[] a){
foreach (char item in a)
{
Console.Write(item);
}
}
static void Main(string[] args)
{
string str = "Hello world!";
char[] arr = { 'I', 'n', 'c', 'l', 'u', 'd', 'H', 'e', 'l', 'p' };
//打印值
Console.WriteLine("Before CopyTo...");
Console.WriteLine("str = " + str);
Console.Write("arr = ");
printCharArray(arr);
Console.WriteLine();
//复制“ Hello”到arr"Hello " to arr
str.CopyTo(0, arr, 0, 6);
//打印值
Console.WriteLine("After CopyTo 1)...");
Console.WriteLine("str = " + str);
Console.Write("arr = ");
printCharArray(arr);
Console.WriteLine();
//复制“ Hello”到arr"World! " to arr
str.CopyTo(6, arr, 0, 6);
//打印值
Console.WriteLine("After CopyTo 1)...");
Console.WriteLine("str = " + str);
Console.Write("arr = ");
printCharArray(arr);
Console.WriteLine();
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
Before CopyTo... str = Hello world! arr = IncludHelp After CopyTo 1)... str = Hello world! arr = Hello Help After CopyTo 1)... str = Hello world! arr = world!Help
参考:String.CopyTo(Int32,Char[],Int32,Int32)方法