Black
Black

Reputation: 20322

How to detect new line?

I try to read a string char by char, and detect if there is any new line, and create an output if this is the case.

strText = "A;B;C" & vbcrlf & "D;E;F"
wscript.echo strText

For i=1 To Len(strText)

    charx = Mid(strText,i,1)

    if charx = "\n" then
        wscript.echo "OMG, NEW LINE DETECTED!!!"
    end if
Next 

I tried it by comparing the readed char with "\n", but this failed.

Upvotes: 1

Views: 1730

Answers (3)

JosefZ
JosefZ

Reputation: 30153

Use InStr function as follows:

option explicit
'On Error Resume Next
On Error GoTo 0
Dim strText, strResult
strResult = Wscript.ScriptName
strText = "A;B;C" & vbcrlf & "D;E;F;vbCrLf"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText
strText = "A;B;C" & vbNewLine & "D;E;F;vbNewLine"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText
strText = "A;B;C" & vbCr & "D;E;F;vbCr"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText
strText = "A;B;C" & vbLf & "D;E;F;vbLf"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText

Wscript.Echo strResult
Wscript.Quit

Function testCrLf( sText)
  If InStr(1, sText, vbCrLf, vbBinaryCompare) Then
    testCrLf = "CrLf detected in "
  Else
    testCrLf = "CrLf not found in "
  End If
End Function

Output:

==>cscript D:\VB_scripts\SO\32411401.vbs
32411401.vbs
--------------------
CrLf detected in A;B;C
D;E;F;vbCrLf
--------------------
CrLf detected in A;B;C
D;E;F;vbNewLine
--------------------
D;E;F;vbCround in A;B;C
--------------------
CrLf not found in A;B;C
D;E;F;vbLf

==>

Upvotes: 3

MC ND
MC ND

Reputation: 70943

if charx = vbLf then
    wscript.echo "OMG, NEW LINE DETECTED!!!"
end if

In vbscript "\n" is a string with two characters, no a new line character

Upvotes: 2

lezhni
lezhni

Reputation: 304

The simple way to identify new line is using Environment.NewLine

Upvotes: -1

Related Questions