split by crlf using VB.net
Need 开发者_运维技巧help how to proper split a string by crlf below is the code:
Dim str As String = "Hello" & vbCrLf & "World"
Dim parts As String() = str.Split(ControlChars.CrLf.ToCharArray)
For Each part As String In parts
MsgBox(part)
Next
Output
Hello
World
I want to get rid the blank space in between the two.
Hello
WorldIf you want to support all kinds of newlines (CR, LF, CR LF) and don’t need blank lines, you can split on both characters and make use of the String.Split
option that stops it from producing empty entries:
str.Split(ControlChars.CrLf.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
(This also produces an empty array if the input is empty.)
If you know you have consistent CR LF newlines and you want to preserve blank lines, you can split on the entire delimiter:
str.Split({ControlChars.CrLf}, StringSplitOptions.None)
The given answer splits on any cr
OR lf
and removes blanks; that works ok for the given case, but it would remove 'real' empty lines as well (and feels unclean to me).
Alternative:
System.Text.RegularExpressions.Regex.Split(str, vbCrLf)
(note that the second string is a regex-pattern, special chars would have to be escaped)
This code will split on line-feed, new line or both(vbCrLf). It will not remove empty lines.
Dim arr() As String = System.Text.RegularExpressions.Regex.Split(text, "(\r\n|\r|\n)", _
RegularExpressions.RegexOptions.ExplicitCapture)
精彩评论