2

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.

Berker Yüceer
  • 7,026
  • 18
  • 68
  • 102

4 Answers4

7

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.

Deanna
  • 23,876
  • 7
  • 71
  • 156
  • A better or more current solution https://stackoverflow.com/a/3977549/4528239 – neosonne Jan 30 '20 at 08:57
  • @neosonne that's is a different language, c# instead of vb6 – Deanna Jan 30 '20 at 09:07
  • it isn't matter, the both languages are doing the same, only with different syntax: `Function GetNumbers(val As String) As String Return CType(val.Where(Function(c) Char.IsDigit(c)).ToArray(), String) End Function` – neosonne Jan 31 '20 at 10:27
  • @neosonne that's not valid VB6 syntax. Note, VB6, not VB.net. – Deanna Jan 31 '20 at 10:31
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
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

You may use regular expressions:

Dim NumExp As New RegExp

NumExp.Pattern = "\D"
NumExp.Global = True

strOutput = NumExp.Replace(strWhatToReplace, strReplaceWithWhat)
tjvg1991
  • 382
  • 1
  • 5
  • 10
0
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