简体   繁体   English

将字符串拆分为两个数组 C#

[英]Split string into two arrays C#

I'd like to split a string into two arrays:我想将一个字符串分成两个数组:

string foo = "apple;carrot";

I want to put "apple" into one array, and "carrot" in another array.我想将“apple”放入一个数组中,将“carrot”放入另一个数组中。

Just using foo.Split(;) would result in both words being put into the same array, one after each other.仅使用foo.Split(;)会导致两个单词一个接一个地放入同一个数组中。

I hope I made myself clear, and thanks in advance.我希望我说清楚了,并提前致谢。

You would need to project the array to a new array for each item:您需要将数组投影到每个项目的新数组:

string foo = "apple;carrot";
var collection = foo.Split(';').Select(x=> new String[] { x });

This will return you IEnumerable<String[]> which you can iterate.这将返回您可以迭代的IEnumerable<String[]>

foreach(var array in collection)
{
  // do something with array
}

Or you can create an array of arrays like this:或者你可以像这样创建一个数组数组:

var arrays = collection.ToArray();
        var splits = foo.Split( new char[]{ ';' });

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

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