繁体   English   中英

C#:将int []转换为字符串的最有效方法

[英]C#: the most efficient way to convert int[] into a string

我知道这种问题已经回答了很多次。 尽管我找到了很多可能的答案,但是它们仍然不能解决我的问题,这是实现将整数数组转换为单个字符串的最快方法 我有例如:

int[] Result = new int[] { 1753387599, 1353678530, 987001 }

我希望将其反转,所以我认为最好在进一步的代码之前加上

Array.Reverse(Result);

尽管我不从结尾进行迭代,但这等效于反转,因为我从结尾开始调用元素。 所以我已经做到了。 只是让您知道-如果您能想到除我以外的任何其他解决方案,我建议您使用Array.Reverse,因为该解决方案必须颠倒。 我始终只关心数字的最后9位-就像模1000000000000。这就是我想要得到的:

987001|353678530|753387599

分隔符现在只是要弄清楚。 我编写了自己的函数,该函数比使用.ToString()快约50%。 tempint-int数组的当前元素,StrArray-字符串数组。 使用StringBuilder或对字符串求和是不值得的,因此最后,我只是简单地加入AnswerArr的元素以获取结果。 IntBase-包含1000个元素的数组,字符串的数字从“ 000”到“ 999”,索引为0到999。

    for (i = 0; i < limit; i++)
    {
    //Some code here

    j = 3 * (limit - i);

    //Done always
    StrArray[j - 1] = IntBase[tempint % 1000];

    if (tempint > 999999) 
    {
        //Done in 99/100 cases
        StrArray[j - 2] = IntBase[tempint % 1000000 / 1000]; 
        StrArray[j - 3] = IntBase[tempint % 1000000000 / 1000000];
    }
    else
    {
        if (tempint > 999) 
        {
            //Done just once
            StrArray[j - 2] = IntBase[tempint % 1000 / 1000];
        }
    }
    }
    //Some code here

    return string.Join(null, StrArray);

在进行此部分操作之前,需要进行大量计算,而且计算速度非常快。 尽管一切都在714毫秒内完成,而没有求和整数,但只有337毫秒。

在此先感谢您的帮助。

最好的问候,伦道夫

快点? 最有效? 我不确定,您应该尝试一下。 但是转换的简单方法

int[] Result = new int[] { 1753387599, 1353678530, 987001 };
var newstr = String.Join("|", Result.Reverse().Select(i => i % 1000000000));

在大多数情况下,我都会建议LB给出答案。 但是,如果您追求最高的效率,这是我的建议:

  • 您可以从末尾迭代数组,因此无需调用任何Reverse
  • IntBase[tempint % 1000000 / 1000]IntBase[tempint % 1000]相同,因为除法的优先级高于模数
  • 我敢打赌,整个IntBase中间步骤会极大地拖慢您的速度

我的建议是这样的-与LB的代码很像,但势在必行且略有优化。

var sb = new StringBuilder();
var ints; // Your int[]

// Initial step because of the delimiters.
sb.Append((ints[ints.Length - 1] % 1000000000).ToString());

// Starting with 2nd last element all the way to the first one.
for(var i = ints.Length - 2; i >= 0; i--)
{
    sb.Append("|");
    sb.Append((ints[i] % 1000000000).ToString());
}

var result = sb.ToString();

暂无
暂无

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

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