【问题标题】:How to detect new line?如何检测新行?
【发布时间】:2015-09-05 09:16:08
【问题描述】:

我尝试逐个字符读取字符串,并检测是否有任何新行,如果是则创建输出。

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 

我尝试将读取的字符与"\n" 进行比较,但失败了。

【问题讨论】:

    标签: for-loop vbscript


    【解决方案1】:

    使用InStr函数如下:

    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
    

    输出

    ==>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
    
    ==>
    

    【讨论】:

      【解决方案2】:
      if charx = vbLf then
          wscript.echo "OMG, NEW LINE DETECTED!!!"
      end if
      

      在vbscript中"\n"是一个有两个字符的字符串,没有换行符

      【讨论】:

      • 谢谢你,这有效。我之前也尝试过vbCrLf,但是没有成功。
      • @EdwardBlack,它不适用于vbCrLf,因为此常量是一个两个字符的字符串,一个回车符后跟一个换行符,但是您正在迭代字符串,一次提取一个字符, 一个字符串不能等于两个字符串。
      【解决方案3】:

      识别新行的简单方法是使用Environment.NewLine

      【讨论】:

      • 我试过if charx = Environment.NewLine then,但我得到一个错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      相关资源
      最近更新 更多