开发者

String splitting produces different results than expected

开发者 https://www.devze.com 2022-12-25 09:58 出处:网络
开发者_高级运维 it returns not what i expected. i expected something like: ab cab ab what am i doing wrong? don\'t do .ToCharArray()

String splitting produces different results than expected

开发者_高级运维

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

ab

cab

ab

what am i doing wrong?


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


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().


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号