Copy one string array to another

霸气de小男生 提交于 2019-12-18 12:20:22

问题


How can I copy a string[] from another string[]?

Suppose I have string[] args. How can I copy it to another array string[] args1?


回答1:


Allocate space for the target array, that use Array.CopyTo():

targetArray = new string[sourceArray.Length];
sourceArray.CopyTo( targetArray, 0 );



回答2:


  • To create a completely new array with the same contents (as a shallow copy): call Array.Clone and just cast the result.
  • To copy a portion of a string array into another string array: call Array.Copy or Array.CopyTo

For example:

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);
    }
}

Assuming we start off with args = { "a", "b", "c", "d", "e", "f", "g", "h" } the results are:

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:


The above answers show a shallow clone; so I thought I add a deep clone example using serialization; of course a deep clone can also be done by looping through the original array and copy each element into a brand new array.

 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);
            }
        }

Testing the deep clone:

 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));
        }


来源:https://stackoverflow.com/questions/886488/copy-one-string-array-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!