I have a string array like this:
string[] Array = new string[3] {"Man(21)", "Woman(33)", "Baby(4)"};
Now I want to split this array into this scheme:
Array = new string[6] {"Man", "21", "Woman", "33", "Baby", "4"};
Anybody have idea?
you can use Split and SelectMany
var result = Array.SelectMany(x => x.Split(new[]
{
'(', ')'
}, StringSplitOptions.RemoveEmptyEntries)).ToArray();
var result = from str in Array
let items = str.Split('(')
from item in items
select item.Replace(")", string.Empty);
You can give a try to regular expressions:
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();
Depending on the use case you might find it more useful to output a list of objects with Name and Age properties, or a dictionary. Here is an example of the former:
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();
The result is:
Name Age
Man 21
Woman 33
Baby 4
NoAge null
Credit to dotctor for the Split command.
var result = arr.Select(s => s.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)).Select(r => new[] { r.First(), r.Skip(1).SingleOrDefault() }).ToList(); But get a 2 dimension var.