如何从另一个 string[]
复制一个 string[]
?
假设我有 string[] args
。如何将它复制到另一个数组 string[] args1
?
最佳答案
- 要创建一个具有相同内容的全新数组(作为浅拷贝):调用
Array.Clone
并只是投出结果。 - 要将字符串数组的一部分复制到另一个字符串数组中:调用
Array.Copy
或Array.CopyTo
例如:
using System;
class Test
{
static void Main(string[] args)
{
// Clone the whole array
string[] args2 = (string[]) args.Clone();
// Copy the five elements with indexes 2-6
// from args into args3, stating from
// index 2 of args3.
string[] args3 = new string[5];
Array.Copy(args, 2, args3, 0, 5);
// Copy whole of args into args4, starting from
// index 2 (of args4)
string[] args4 = new string[args.Length+2];
args.CopyTo(args4, 2);
}
}
假设我们从 args = { "a", "b", "c", "d", "e", "f", "g", "h"
结果是:
args2 = { "a", "b", "c", "d", "e", "f", "g", "h" }
args3 = { "c", "d", "e", "f", "g" }
args4 = { null, null, "a", "b", "c", "d", "e", "f", "g", "h" }
关于c# - 将一个字符串数组复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/886488/