简体   繁体   English

c#-将字符串拆分为2个数组的有效方法是什么

[英]c# - what is the efficient way to split string to 2 arrays

i have a string like "1,2,3,4,5,6,7" . 我有一个像"1,2,3,4,5,6,7"的字符串。

always 7 numbers ! 总是7个数字! seperated by , 通过分隔,

what is the best way to split it into 2 arrays of integers , 将其拆分为2个整数数组的最佳方法是什么,

the firts array contain 1-5 numbers firts数组包含1-5个数字

the second array contain 6-7 numbers 第二个数组包含6-7个数字

thanks 谢谢

var numString = "1,2,3,4,5,6,7";
var numArray = numString.Split(',');
var array1 = numArray.Take(5).ToArray();
var array2 = numArray.Skip(5).ToArray();

or if you want an array of int s. 或者如果您想要一个int数组。

var numString = "1,2,3,4,5,6,7";
var numArray = numString.Split(',');
var array1 = numArray.Take(5).Select(s => int.Parse(s)).ToArray();
var array2 = numArray.Skip(5).Select(s => int.Parse(s)).ToArray();

Note that you can skip .ToArray() if you don't require an array. 请注意,如果不需要数组,则可以跳过.ToArray()

Edit: 编辑:
Actually, the fastest code I can come up with is 实际上,我能想到的最快的代码是

var numString = "1,2,3,4,5,6,7";
var numArray = numString.Split(',');

var array1 = new int[5];
var array2 = new int[2];

array1[0] = int.Parse(numArray[0]);
array1[1] = int.Parse(numArray[1]);
array1[2] = int.Parse(numArray[2]);
array1[3] = int.Parse(numArray[3]);
array1[4] = int.Parse(numArray[4]);
array2[0] = int.Parse(numArray[5]);
array2[1] = int.Parse(numArray[6]);

It is approximately 60% faster than the first version. 它比第一个版本快60%。
I compared the speed of Jason's version, with and without ToArray after the Select, both are 15-20% slower. 我比较了选择后使用和不使用ToArray的Jason版本的速度,两者都慢了15-20%。
The first because int.Parse() is called 12 times instead of 7, the second because the extra .ToArray() . 第一个因为int.Parse()被调用了12次而不是7次,第二个因为额外的.ToArray()被调用了。

Here is my benchmark code 这是我的基准代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Stackoverflow_Test
{
    class TestToArrayVsEnumerator
    {
        private const string numString = "1,2,3,4,5,6,7";
        private readonly string[] numArray;
        private const int iterations = 100000;
        private const int numTests = 10;

        public TestToArrayVsEnumerator()
        {
            numArray = numString.Split(',');
        }

        public void Run()
        {
            System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
            Console.WriteLine("Warmup");
            RunTest(WithEnumerator);
            RunTest(WithSelectFirst);
            RunTest(WithSelectToArray);
            RunTest(StraightForward);

            Console.WriteLine("--- test start ---");
            StringBuilder sb = new StringBuilder();
            foreach (var t in Enumerable.Range(0, numTests))
            {
                var timeEnumerator = RunTest(WithEnumerator);
                var timeWithSelectFirst = RunTest(WithSelectFirst);
                var timeWithSelectToArray = RunTest(WithSelectToArray);
                var timeStraightForward = RunTest(StraightForward);

                sb.AppendLine("WithEnumerator, " + timeEnumerator.TotalMilliseconds + " ms. "
                    + "WithSelectFirst, " + timeWithSelectFirst.TotalMilliseconds + " ms. (" + ((100 * ((double)timeWithSelectFirst.Ticks / (double)timeEnumerator.Ticks)) - 100) + "%) "
                    + "WithSelectToArray, " + timeWithSelectToArray.TotalMilliseconds + " ms. (" + ((100 * ((double)timeWithSelectToArray.Ticks / (double)timeEnumerator.Ticks)) - 100) + "%) "
                    + "StraightForward, " + timeStraightForward.TotalMilliseconds + " ms. (" + ((100 * ((double)timeStraightForward.Ticks / (double)timeEnumerator.Ticks)) - 100) + "%) "
                    );
            }
            Console.WriteLine(sb.ToString());
            MessageBox.Show(sb.ToString());
            Console.WriteLine("--- test end ---");
        }

        private TimeSpan RunTest(Action test)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            foreach (var i in Enumerable.Range(0, iterations))
            {
                test();
            }
            sw.Stop();
            return sw.Elapsed;
        }

        public void WithEnumerator()
        {
            var array1 = numArray.Take(5).Select(s => int.Parse(s)).ToArray();
            var array2 = numArray.Skip(5).Select(s => int.Parse(s)).ToArray();
        }

        public void WithSelectFirst()
        {
            var intArray = numArray.Select(s => int.Parse(s)).ToArray();
            var array1 = numArray.Take(5).ToArray();
            var array2 = numArray.Skip(5).ToArray();
        }

        public void WithSelectToArray()
        {
            var intArray = numArray.Select(s => int.Parse(s)).ToArray();
            var array1 = numArray.Take(5).ToArray();
            var array2 = numArray.Skip(5).ToArray();
        }

        public void StraightForward()
        {
            var array1 = new int[5];
            var array2 = new int[2];

            array1[0] = int.Parse(numArray[0]);
            array1[1] = int.Parse(numArray[1]);
            array1[2] = int.Parse(numArray[2]);
            array1[3] = int.Parse(numArray[3]);
            array1[4] = int.Parse(numArray[4]);
            array2[0] = int.Parse(numArray[5]);
            array2[1] = int.Parse(numArray[6]);
        }
    }
}

with the result (release code, start with no debugging) 结果(发布代码,不调试开始)

WithEnumerator, 446,3176 ms. WithSelectFirst, 538,4354 ms. (20,639517688749%)  WithSelectToArray, 505,5178 ms. (13,2641419473487%) StraightForward, 178,6037 ms. (-59,9828238904314%)     
WithEnumerator, 445,463 ms.  WithSelectFirst, 528,0676 ms. (18,5435378471388%) WithSelectToArray, 525,6011 ms. (17,9898442743842%) StraightForward, 181,1559 ms. (-59,3331208203599%)     
WithEnumerator, 454,5901 ms. WithSelectFirst, 526,0643 ms. (15,722779708577%)  WithSelectToArray, 524,5135 ms. (15,3816372155927%) StraightForward, 185,8895 ms. (-59,1083263801829%)     
WithEnumerator, 442,4805 ms. WithSelectFirst, 525,8961 ms. (18,8518138087441%) WithSelectToArray, 558,0706 ms. (26,1232076893784%) StraightForward, 208,8639 ms. (-52,7970385135616%)     
WithEnumerator, 454,3597 ms. WithSelectFirst, 528,4238 ms. (16,3007634699997%) WithSelectToArray, 531,6279 ms. (17,0059536530198%) StraightForward, 185,5925 ms. (-59,1529574475905%)     
WithEnumerator, 452,76 ms.   WithSelectFirst, 542,3876 ms. (19,7958300203198%) WithSelectToArray, 553,0012 ms. (22,1400300379892%) StraightForward, 184,5231 ms. (-59,2448316989133%)     
WithEnumerator, 468,6732 ms. WithSelectFirst, 528,5409 ms. (12,7738688706758%) WithSelectToArray, 549,7821 ms. (17,3060674260871%) StraightForward, 188,0931 ms. (-59,8668965923377%)     
WithEnumerator, 489,7136 ms. WithSelectFirst, 560,0267 ms. (14,3580043519314%) WithSelectToArray, 556,3374 ms. (13,6046456541129%) StraightForward, 177,8818 ms. (-63,6763610404122%)     
WithEnumerator, 462,5361 ms. WithSelectFirst, 552,7817 ms. (19,5110392464502%) WithSelectToArray, 548,7365 ms. (18,6364696723131%) StraightForward, 180,1382 ms. (-61,054239874466%)     
WithEnumerator, 462,787 ms.  WithSelectFirst, 536,089 ms.  (15,8392521829697%) WithSelectToArray, 543,2204 ms. (17,3802202741218%) StraightForward, 180,4709 ms. (-61,0034637965198%) 
string someString = "1,2,3,4,5,6,7";
var numbers = someString.Split(',')
                         .Select(s => Int32.Parse(s));
int[] firstFive = numbers.Take(5).ToArray();
int[] afterFirstFive = numbers.Skip(5).ToArray();
var n = "1,2,3,4,5,6,7".Split(',');
var first5 = n.Take(5).ToArray();
var last2 = n.Skip(5).ToArray();

If you want to convert them to integers, you could do something like this: 如果要将它们转换为整数,可以执行以下操作:

  string x = "1,2,3,4,5,6,7";
  var f = x.Split(',').Take(5).Select(s => { int v; if (!Int32.TryParse(s, out v)) v = -1; return v; });
  var g = x.Split(',').Skip(5).Select(s => { int v; if (!Int32.TryParse(s, out v)) v = -1; return v; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM