Math Student
Math Student

Reputation: 567

Append arrays and lists

For example, if the entered input is:

1 2 3 |4 5 6 | 7 8

we should manipulate it to

1 2 3|4 5 6|7 8

Another example:

7 | 4 5|1 0| 2 5 |3

we should manipulate it to

7|4 5|1 0|2 5|3

This is my idea because I want to exchange some of the subarrays (7; 4 5; 1 0; 2 5; 3).

I'm not sure that this code is working and it can be the base of I want to do but I must upload it for you to see my work.

static void Main(string[] args)
{
    List<string> arrays = Console.ReadLine()
        .Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .ToList();

    foreach (var element in arrays)
    {
        Console.WriteLine("element: " + element);
    }
}

Upvotes: 0

Views: 66

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

This could do this with a simple regular expression:

var result = Regex.Replace(input, @"\s?\|\s?", "|");

This will match any (optional) white space character, followed by a | character, followed by an (optional) white space character and replace it with a single | character.

Alternatively, if you need to potentially strip out multiple spaces around the |, replace the zero-or-one quantifiers (?) with zero-or-more quantifiers (*):

var result = Regex.Replace(input, @"\s*\|\s*", "|");

To also deal with multiple spaces between numbers (not just around | characters), I'd recommend something like this:

var result = Regex.Replace(input, @"\s*([\s|])\s*", "$1")

This will match any occurrence of zero or more white space characters, followed by either a white space character or a | character (captured in group 1), followed by zero or more white space characters and replace it with whatever was captured in group 1.

Upvotes: 2

Aleks Andreev
Aleks Andreev

Reputation: 7054

You need to split your input by "|" first and then by space. After this, you can reassemble your input with string.Join. Try this code:

var input = "1 2 3 |4 5 6 | 7 8";
var result = string.Join("|", input.Split('|')
  .Select(part => string.Join(" ", 
    part.Trim().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries))));

// now result is "1 2 3|4 5 6|7 8"

Upvotes: 2

Related Questions