0

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

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

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.