Varyanica
Varyanica

Reputation: 409

String splitting produces different results than expected

alt text

it returns not what i expected. i expected something like:

ab
cab
ab

what am i doing wrong?

Upvotes: 5

Views: 595

Answers (6)

Mr_Hic-up
Mr_Hic-up

Reputation: 389

My understanding is that the string char sequence you provide to the Split method is a list of delimiter characters, not a single delimiter madeof several characters.

In your case, Split consider the '\r' and '\n' characters as delimiters. So when it encounters the '\r\n' sequence, it returns the string between those 2 delimiters, an empty string.

Upvotes: 0

Jonas Elfström
Jonas Elfström

Reputation: 31458

Environment.NewLine is probably the way to go but if not this works

var ab = "a\r\nb\r\nc";
var abs = ab.Split(new[]{"\r\n"}, StringSplitOptions.None);

Upvotes: 1

This option also works, string [] b = Regex.Split(abc, "\r\n");

Upvotes: 0

Fredou
Fredou

Reputation: 20140

don't do .ToCharArray()

it will split \r then \n

that why you have empty value

something like this should work

var aa = ("a" & Environment.NewLine & "b" & Environment.NewLine & "c").Split(New String[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 7

evgeniuz
evgeniuz

Reputation: 2769

You just splitting the string using \r or \n as delimiters, not the \r\n together.

Upvotes: 1

Jens
Jens

Reputation: 25593

Since you are splitting on "\r" and "n", String.Split extracts the empty string from "\r\n".

Take a look at StringSplitOptions.RemoveEmptyEntries or use new String[] { "\r\n" } instead of "\r\n".ToCharArray().

Upvotes: 6

Related Questions