0

I have a string like this: string ip = "192.168.10.30 | SomeName". I want to split it by the | (including the spaces. With this code it is not possible unfortunately:

string[] address = ip.Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries);

as this leads to "192.168.10.30 ". I know I can add .Trim() to address[0] but is that really the right approach?

Simply adding the spaces(' | ') to the search pattern gives me an

Unrecognized escape sequence

2
  • 2
    You may want to use: msdn.microsoft.com/en-us/library/8yttk7sy(v=vs.110).aspx Commented Nov 10, 2016 at 8:14
  • 1
    You might use regex with this pattern. (?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) *\| *(?<name>\S*). for example to get ip write regex.Match(input).Groups["ip"] and to get name write name instead of ip Commented Nov 10, 2016 at 8:23

3 Answers 3

12

You can split by string, not by character:

var result = ip.Split(new string[] {" | "}, StringSplitOptions.RemoveEmptyEntries);
Sign up to request clarification or add additional context in comments.

1 Comment

The char[] { '|',' '} approach is more robust, as it covers the case of missing spaces and empty entries (which may or may not be relevant to the OP, but it's worth to know)
3

The Split method accepts character array, so you can specify the second character as well in that array. Since you ware used RemoveEmptyEntries those spaces will be removed from the final result.

Use like this :

 string[] address = ip.Split(new char[] { '|',' '}, StringSplitOptions.RemoveEmptyEntries);

You will get two items in the array

"192.168.10.30" and SomeName

Comments

0

This might do the trick for you

string[] address = ip.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.