【问题标题】:Replace everything except numbers in a string vb6替换字符串vb6中除数字之外的所有内容
【发布时间】:2011-12-21 12:20:01
【问题描述】:

好吧,我做了研究,看到了很多关于这个的帖子,但在 VB6 中找不到解决方案 那么我该如何在 VB6 中做到这一点?

假设我得到了一个类似的字符串:

“从前,有一个小孩想知道离家比1000更远...”

我只想得到 numbers "1000" 在这个字符串中与字符串分离,并想替换整个字符串,但数字应该保持不变。

【问题讨论】:

    标签: string vb6 replace


    【解决方案1】:

    最简单的方法是遍历字符串并将数字复制到一个新的:

    Function GetNumbers(Value As String) As String
    Dim Index As Long
    Dim Final As String
    
      For Index = 1 To Len(Value)
        If Mid(Value, Index, 1) Like "[0-9]" Then
          Final = Final & Mid(Value, Index, 1)
        End If
      Next
    
      GetNumbers = Final
    End Function
    

    结果:

    ?GetNumbers("abc12def345")
    12345
    

    但是,当有很多数字时,这对于长字符串来说效率很低。

    【讨论】:

    • 一个更好或更新的解决方案stackoverflow.com/a/3977549/4528239
    • @neosonne 那是另一种语言,c# 而不是 vb6
    • 没关系,两种语言都是一样的,只是语法不同:Function GetNumbers(val As String) As String Return CType(val.Where(Function(c) Char.IsDigit(c)).ToArray(), String) End Function
    • @neosonne 这不是有效的 VB6 语法。注意,VB6,不是 VB.net。
    【解决方案2】:

    以迪安娜的回答为基础:

    Function GetNumbers(Value As String) As String
    Dim Index As Long
    Dim Digit As String
    Dim Final As String
    Dim Count As Long
    
      Count = 1
      GetNumbers = Space(Len(Value))
      For Index = 1 To Len(Value)
        Digit = Mid(Value, Index, 1)
        If Digit Like "[0-9]" Then
          Mid(GetNumbers, Count, 1) = Digit
          Count = Count + 1
        End If
      Next
    
      GetNumbers = Left(GetNumbers, Count - 1)
    End Function
    

    这个函数应该是O(n)

    ?GetNumbers("abc12def345")
    12345
    

    【讨论】:

    • 还有更高效的版本。因为我很懒,所以我把它作为练习留给读者:p
    【解决方案3】:

    你可以使用正则表达式:

    Dim NumExp As New RegExp
    
    NumExp.Pattern = "\D"
    NumExp.Global = True
    
    strOutput = NumExp.Replace(strWhatToReplace, strReplaceWithWhat)
    

    【讨论】:

      【解决方案4】:
      nStr = "abc12def345"
      For X = 1 To Len(nStr)
          If IsNumeric(Mid(nStr, X, 1)) = True Then
              nNum = nNum & Mid(nStr, X, 1)
          End If
      Next X
      
      
      MsgBox nNum
      

      【讨论】:

        猜你喜欢
        • 2018-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-24
        相关资源
        最近更新 更多