2

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?

4 Answers 4

4

you can use Split and SelectMany

var result = Array.SelectMany(x => x.Split(new[]
    {
        '(', ')'
    }, StringSplitOptions.RemoveEmptyEntries)).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@downvoter: Why a downvote? This also produces the desired result.
0

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

Comments

0

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.

2 Comments

what we need to do if we don't want to have result with this scheme: "Name=Man,Age=21" and just see "Man,21"
I used this code instead of yours: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.