How do I replace numbers in a string with "#"?
-Zach
Printable View
How do I replace numbers in a string with "#"?
-Zach
NVM I'm smart and I got it.
-Resolved-
How about using the Replace function?Quote:
Originally Posted by Zach_VB6
I didn't know how to identify the numbers.
I used:
Code:Public Function RemoveNumbers(ByVal sString As String) As String
Dim lLen As Long, sTemp As String, sFinal As String
sFinal = sString
For lLen = 1 To Len(sString)
sTemp = Mid$(sString, lLen, 1)
If IsNumeric(sTemp) Then sFinal = Replace(sFinal, sTemp, "#", , 1)
Next
RemoveNumbers = sFinal
End Function
That would be slow. Does this need to be optimized? Are there speed considerations?
The numbers (digits 0 thru 9) are character codes 48 thru 57.Quote:
Originally Posted by Zach_VB6
This is fast:
This is faster:Code:Private Function MaskNumbers(sString As String) As String
Dim i As Long, lPos As Long, strChar As String
MaskNumbers = sString
For i = 48 To 57 ' Character codes for digits "0" thru "9"
strChar = Chr$(i)
lPos = InStr(1, MaskNumbers, strChar) ' Find first matching character
Do Until lPos = 0
Mid(MaskNumbers, lPos, 1) = "#" ' Change the character
lPos = InStr(lPos + 1, MaskNumbers, strChar) ' Find next character
Loop
Next i
End Function
Code:Private Function MaskNumbers(sString As String) As String
Dim btChars() As Byte, i As Long
btChars = sString ' Convert string to byte array
For i = 0 To UBound(btChars) Step 2 ' Step 2 because it's unicode
Select Case btChars(i) ' Check character code
Case 48 To 57 ' If it's a digit
' It's only a digit if the high byte is zero
If btChars(i + 1) = 0 Then btChars(i) = 35 ' Change the character code to that of "#"
End Select
Next i
MaskNumbers = btChars ' Convert to string
End Function