代码之家  ›  专栏  ›  技术社区  ›  Arunachalam

将一个字符串数组复制到另一个字符串数组

  •  17
  • Arunachalam  · 技术社区  · 17 年前

    我怎样才能复制 string[] 从另一个 字符串[ ] ?

    假设我有 string[] args . 如何将其复制到其他数组 string[] args1 ?

    3 回复  |  直到 10 年前
        1
  •  20
  •   sharptooth    17 年前

    为使用array.copyto()的目标数组分配空间:

    targetArray = new string[sourceArray.Length];
    sourceArray.CopyTo( targetArray, 0 );
    
        2
  •  29
  •   Jon Skeet    17 年前
    • 要创建具有相同内容的全新数组(作为浅副本):调用 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" } 
    
        3
  •  0
  •   dragonfly02    11 年前

    上面的答案显示了一个浅克隆;所以我想我使用序列化添加了一个深克隆示例;当然,通过循环遍历原始数组并将每个元素复制到一个全新的数组中,也可以完成一个深克隆。

     private static T[] ArrayDeepCopy<T>(T[] source)
            {
                using (var ms = new MemoryStream())
                {
                    var bf = new BinaryFormatter{Context = new StreamingContext(StreamingContextStates.Clone)};
                    bf.Serialize(ms, source);
                    ms.Position = 0;
                    return (T[]) bf.Deserialize(ms);
                }
            }
    

    测试深克隆:

     private static void ArrayDeepCloneTest()
            {
                //a testing array
                CultureInfo[] secTestArray = { new CultureInfo("en-US", false), new CultureInfo("fr-FR") };
    
                //deep clone
                var secCloneArray = ArrayDeepCopy(secTestArray);
    
                //print out the cloned array
                Array.ForEach(secCloneArray, x => Console.WriteLine(x.DateTimeFormat.DateSeparator));
    
                //modify the original array
                secTestArray[0].DateTimeFormat.DateSeparator = "-";
    
                Console.WriteLine();
                //show the (deep) cloned array unchanged whereas a shallow clone would reflect the change...
                Array.ForEach(secCloneArray, x => Console.WriteLine(x.DateTimeFormat.DateSeparator));
            }