principal-ideal-domain
principal-ideal-domain

Reputation: 4276

Split string into lines

I want to split a string into lines. For a long time I was using

Split(myString, vbCrLf)

But now I ran into some problems because there are different characters used for a new line. I want to match all those characters (\n and \r\n, ...). What shall I do?

Upvotes: 4

Views: 2829

Answers (1)

SierraOscar
SierraOscar

Reputation: 17637

Replace them all with another character. In this example I'll use Chr(19) which is an uncommon ASCII character.

myString = Replace(myString, vbCr, Chr(19))
myString = Replace(myString, vbLf, Chr(19))
myString = Replace(myString, vbCrLf, Chr(19))

'// Remove any doubled up Chr(19)
While InStr(myString, Chr(19) & Chr(19))
    myString = Replace(myString, Chr(19) & Chr(19), Chr(19))
Wend

'// Remove any trailing Chr(19) if present
y = Split(Left$(myString, Len(myString) - IIf(Right$(myString, 1) = Chr(19), 1, 0)), Chr(19))

For Each s In y
    Debug.Print s & ": " & Len(s)
Next

Upvotes: 5

Related Questions