15

如下图所示,将字符串数组中的各个字符分隔strArr成这些字符数组的最佳方法是什么?charArr

string[] strArr = { "123", "456", "789" };
char[] chrArr = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };

这是我目前正在做的,但我认为它不是很优雅:

int characterCount = 0;

for (int i = 0; i < strArr.Length; i++)
{
    characterCount += strArr[i].Length;
}

int indexCount = 0;
char[] chrArr = new char[characterCount];

for (int i = 0; i < strArr.Length; i++)
{
    for (int j = 0; j < strArr[i].Length; j++)
    {
        chrArr[indexCount] = strArr[i][j];
        indexCount++;
    }
}
4

6 回答 6

42

好吧,最简单的方法是:

char[] chrArr = string.Join(string.Empty, strArr).ToCharArray();

为了确保这里没有混淆性能特征,这里有一个在LINQPad中测试的简短程序(不要忘记在右下角打开优化):

static string[] strArr = { "123", "456", "789" };

void Main()
{
    const int iterations = 10000000; // 10 million

    // Warm up JITter
    StringJoin();
    LINQSelectMany();
    LINQ();

    Stopwatch sw = Stopwatch.StartNew();
    for (int index = 0; index < iterations; index++)
        StringJoin();
    sw.Stop();
    sw.ElapsedMilliseconds.Dump("String.Join");

    sw.Restart();
    for (int index = 0; index < iterations; index++)
        LINQSelectMany();
    sw.Stop();
    sw.ElapsedMilliseconds.Dump("LINQ SelectMany");

    sw.Restart();
    for (int index = 0; index < iterations; index++)
        LINQ();
    sw.Stop();
    sw.ElapsedMilliseconds.Dump("LINQ");
}

public static void StringJoin()
{
    char[] c = string.Join(string.Empty, strArr).ToCharArray();
}

public static void LINQSelectMany()
{
    char[] c = strArr.SelectMany(s => s).ToArray();
}

public static void LINQ()
{
    var characters = (from s in strArr
                      from c in s
                      select c).ToArray();

}

如果您想使用它,可以在此处下载此 LINQPad 脚本。

输出(以毫秒为单位):

String.Join 
765 

LINQ SelectMany 
5098 

LINQ 
5465 

(关于性能测量代码的常见警告在这里适用,指出我犯的任何错误)

于 2013-05-30T20:06:31.007 回答
19

我会做:

char[] chrArr = strArr.SelectMany(s => s).ToArray();
于 2013-05-30T20:07:38.683 回答
7
var res = strArr.SelectMany(c => c.ToCharArray()).ToArray();
于 2013-05-30T20:07:25.223 回答
3

基于 LINQ 的版本将是:

var input = new string[] { "abc", "def", "ghi" };
var characters = (from s in input
                  from c in s
                  select c).ToArray();

foreach (var c in characters) Console.WriteLine(c);
于 2013-05-30T20:09:45.840 回答
1

这基本上是 Jesse Slicer 答案的延伸。

简单地用 ReSharper 清理你的代码(如果你没有这个或类似的东西,现在就去获取它)会产生这样的结果:

var characterCount = strArr.Sum(t => t.Length);

var indexCount = 0;
var chrArr = new char[characterCount];

foreach (var t1 in strArr.SelectMany(t => t))
{
    chrArr[indexCount] = t1;
    indexCount++;
}

foreach只是填充一个数组,并且已经有一个 LINQ 方法ToArray。然后characterCountindexCount是完全没有必要的。

var chrArr = strArr.SelectMany(t => t).ToArray();
于 2013-05-30T20:29:12.500 回答
0

尝试这个..

 string value="";
 string[] strArr = { "123", "456", "789" }; //Your string array.

 for(int i=0;i<strArr.Length;i++)
 {
     value+=strArr[i];
 }
  char [] array=value.ToCharArray();
于 2013-05-31T07:24:55.747 回答