我似乎无法弄清楚这一点。
我想转换一下:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
到二维数组(或列表),看起来像这样:
fooBarArray[0] = Array['Foo', "bar"];
fooBarArray[1] = Array['Foo', "bar"];
fooBarArray[2] = Array['Foo', "bar"];
... etc.
我试过通过(“],”)拆分,然后清理字符串并在之后创建一个数组。但这只是该死的UGLY!
我想要一个更干净的版本。在C#中没有内置这种方法的方法吗?
//谢谢
答案 0 :(得分:2)
首先,将其拆分为"[[", "], [", "]]"
var array1 = foobarString.Split(new string[] {"[[", "], [", "]]"}, StringSplitOptions.RemoveEmptyEntries);
array1
将包含"'Foo', 'bar'"
,"'Foo', 'bar'"
,"'Foo', 'bar'"
然后,您可以按','
var fooBarArray = array1.Select(x => x.Split(',').ToArray()).ToArray()
你可以在一行中完成
var fooBarArray = foobarString.Split(new string[] { "[[", "], [", "]]" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(',').ToArray()).ToArray()
答案 1 :(得分:2)
由于您的问题没有给我们足够的信息,我将假设您正在尝试将一些JSON转换为字符串数组。 据我所知,C#中没有构建方法。 您可以使用扩展名。 Newtonsoft JSON
安装此软件包后,您将能够使用以下代码:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<string[][]>(foobarString);
答案 2 :(得分:1)
您可以使用Regex从源字符串中获取数组元素,然后将匹配项转换为数组。这样的事情可以解决问题:
var input = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
// search for [' more than one word character, put them into group a ',
// more than one whitespace ' more than one word character, put them into group b ']
var arrayMatches = Regex.Matches(input, @"\['(?<a>[\w]+)',\s+'(?<b>[\w]+)'\]");
var arrays = new List<string[]>();
foreach (Match arrayMatch in arrayMatches)
{
// if the match was unsuccessful, take the next match
if(!arrayMatch.Success)
continue;
// create a new string array with element in group a as first element and the element in groub b as the second one
var array = new [] {arrayMatch.Groups["a"].Value, arrayMatch.Groups["b"].Value};
arrays.Add(array);
}
// convert list to array
return arrays.ToArray();
答案 3 :(得分:0)
在那里你可以找到一些例子。 String.Split函数返回一个数组,以便您可以执行
string[] lines = foobarString.Split(new char[]{']'}, StringSplitOptions.RemoveEmtpyEntries);
fooBarArray[0] = lines[i].Split(new char[]{'[',']', ','}, StringSplitOptions.RemoveEmtpyEntries);
看一下这个主题:multidimensional-array-vs
答案 4 :(得分:0)
{
const string oldString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<List<string>>>(oldString);
}