1

I have such a string

|   7   |      2       |39,93 |

and I need to split it into an array where the first element is "7", second "2" and third is "39,93"

I've came up with the following solution

var line     =  "|   7   |      2       |39,93 |";
line = line.Remove(0, 1);
string[] arr = Regex.Replace(line, @"\s+", "").Trim().Split('|');

I wonder if there is a better way to do this.

2
  • Can it be List<double>? Commented Mar 8, 2017 at 14:38
  • take a look at string.split(), then use trim() for the spaces. Commented Mar 8, 2017 at 14:42

2 Answers 2

8

You don't need regex for this, you can do it using String.Split and some LINQ like:

var line = "|   7   |      2       |39,93 |";
var array = line.Split(new[] { '|'}, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => s.Trim()).ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

@xanatos, why ? The OP needs, 3 elements in the array
Hadn't seen the RemoveEmptyEntries... That could generate problems if there are empty columns...
by the time visual studio loaded + started a new console application + verified my soltuion works, you already posted it. +1 for you, -1 for visual studio 2017.
Or if whitespace is the only extraneous char just line.Replace(" ", "").Split(...
1

Yes.

var output =
    line.Split("|") // split on the pipes
        .Select(x => x.Trim()) // remove excess whitespace from each item
        .Where(x => !string.IsNullOrEmpty(x)) // remove any empty items
        .ToArray(); // convert to array

Regexes don't really help you very much here. You could do it with a regex, but it'd probably be harder to read. There's a possibility it might be more efficient though. You'd have to test that.

I'm anticipating empty items appearing at the start and end that need to be dropped because of those initial and terminal pipes, but if there are empty elements in the middle that you wanted to keep you'd have to adjust that part.

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.