将字符串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++;
}
}
答案 0 :(得分: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脚本here。
输出(以毫秒为单位):
String.Join
765
LINQ SelectMany
5098
LINQ
5465
(关于性能测量代码的常见警告适用于此处,指出我所犯的任何错误)
答案 1 :(得分:19)
我愿意:
char[] chrArr = strArr.SelectMany(s => s).ToArray();
答案 2 :(得分:7)
var res = strArr.SelectMany(c => c.ToCharArray()).ToArray();
答案 3 :(得分: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);
答案 4 :(得分: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
。然后characterCount
和indexCount
完全没必要。
var chrArr = strArr.SelectMany(t => t).ToArray();
答案 5 :(得分: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();