Ehsan Davoudi
Ehsan Davoudi

Reputation: 81

Split array into another array

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?

Upvotes: 2

Views: 665

Answers (4)

Stephen Kennedy
Stephen Kennedy

Reputation: 21548

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.

Upvotes: 0

Anton Sizikov
Anton Sizikov

Reputation: 9240

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();

Upvotes: 0

bjaksic
bjaksic

Reputation: 3313

var result = from str in Array
let items = str.Split('(')
from item in items
select item.Replace(")", string.Empty);

Upvotes: 1

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

you can use Split and SelectMany

var result = Array.SelectMany(x => x.Split(new[]
    {
        '(', ')'
    }, StringSplitOptions.RemoveEmptyEntries)).ToArray();

Upvotes: 4

Related Questions