我有一个像这样的字符串数组:
string[] Array = new string[3] {"Man(21)", "Woman(33)", "Baby(4)"};
现在我想把这个数组拆分成这个方案:
Array = new string[6] {"Man", "21", "Woman", "33", "Baby", "4"};
有人有想法吗?
答案 0 :(得分:4)
您可以使用Split和SelectMany
var result = Array.SelectMany(x => x.Split(new[]
{
'(', ')'
}, StringSplitOptions.RemoveEmptyEntries)).ToArray();
答案 1 :(得分:1)
var result = from str in Array
let items = str.Split('(')
from item in items
select item.Replace(")", string.Empty);
答案 2 :(得分:0)
您可以尝试使用正则表达式:
var pattern = @"(?<person>\w+)\((?<age>\d+)\)";
var Array = new string[3] { "Man(21)", "Woman(33)", "Baby(4)" };
Array = Array.SelectMany(item =>
{
var match = Regex.Match(item, pattern, RegexOptions.IgnoreCase);
var person = match.Groups["person"].Value;
var age = match.Groups["age"].Value;
return new List<string>{person, age};
}).ToArray();
答案 3 :(得分:0)
根据用例,您可能会发现输出具有Name
和Age
属性的对象列表或字典更有用。以下是前者的一个例子:
string[] arr = new[] { "Man(21)", "Woman(33)", "Baby(4)", /* test case */ "NoAge" };
var result = arr.Select(s => s.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)).Select(r => new
{
Name = r.First(),
Age = r.Skip(1).SingleOrDefault()
}).ToList();
结果是:
姓名年龄
Man 21
女人33
宝贝4
NoAge null
感谢dot Split
命令。