PrimuS PrimuS - 25 days ago 8
C# Question

How to split a string by multiple chars?

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

Answer

You can split by string, not by character:

var result = ip.Split(new string[] {" | "}, StringSplitOptions.RemoveEmptyEntries);
Comments