Replace everything except numbers in a string vb6

杀马特。学长 韩版系。学妹 提交于 2020-01-15 06:19:30

问题


well i did my research and seen a lot of posts about this but couldnt find a solution in VB6 so how can i do this in VB6?

lets say i got a string like:

" Once upon a time there was a little kid who wonders about going further than 1000 of miles away from home... "

i want to get only numbers "1000" in this string seperated from string and wanna replace the whole string but numbers should stand still.


回答1:


The simplest way is to walk the string and copy numbers to a new one:

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

The result:

?GetNumbers("abc12def345")
12345

This is inefficient with long strings when there are lots of numbers though.




回答2:


Building on Deanna's answer:

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

This function should be O(n)

?GetNumbers("abc12def345")
12345



回答3:


You may use regular expressions:

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


来源:https://stackoverflow.com/questions/8589746/replace-everything-except-numbers-in-a-string-vb6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!