Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strip spaces and punctuation out of string

Status
Not open for further replies.

kayek

Programmer
Jun 19, 2003
95
US
What is a good way to strip out punctuation and spaces from a string? For Example...

name1 = "John J. Van North"
name2 = "John J VanNorth"

I want to be able to strip out the spaces and any punctuation so that I can tell that both these names are the same. I am trying to eliminate dups.

Kaye
 

Function strip_non_chars(input_string) As String
'Remove none alphabetic characters from the machinename
Dim arrCode() As String
Dim X As Integer
Dim n As Integer
Dim lChar As String
Dim iChar As Integer
Dim lWord As String

arrCode = Split(input_string, " ")

For X = LBound(arrCode) To UBound(arrCode)
lWord = CStr(arrCode(X))
For n = 1 To Len(lWord)
lChar = Mid(lWord, n, 1)
iChar = Asc(lChar)
If iChar >= 65 And iChar <= 90 Then
'UPPER CASE Letter
strip_non_chars = strip_non_chars & Chr(iChar)
ElseIf iChar >= 97 And iChar <= 122 Then
'lower case Letter
strip_non_chars = strip_non_chars & Chr(iChar)
Else
'NOT a letter
strip_non_chars = strip_non_chars ' ie do nothing
End If
Next n
strip_non_chars = strip_non_chars & &quot; &quot;
Next X
strip_non_chars = Trim(strip_non_chars)

End Function
 
I found another way to do it from Microsoft's knowlegebase.

' --------------------------------------------------
' Function StripString()
'
' Returns a string minus a set of specified chars.
' --------------------------------------------------
Function StripString(MyStr As Variant) As Variant
On Error GoTo StripStringError

Dim strChar As String, strHoldString As String
Dim i As Integer

' Exit if the passed value is null.
If IsNull(MyStr) Then Exit Function

' Exit if the passed value is not a string.
If VarType(MyStr) <> 8 Then Exit Function

' Check each value for invalid characters.
For i = 1 To Len(MyStr)
strChar = Mid$(MyStr, i, 1)
Select Case strChar
Case &quot;.&quot;, &quot;#&quot;, &quot;,&quot;, &quot;-&quot;, &quot; &quot;
' Do nothing
Case Else
strHoldString = strHoldString & strChar
End Select
Next i

' Pass back corrected string.
StripString = strHoldString

StripStringEnd:
Exit Function

StripStringError:
MsgBox Error$
Resume StripStringEnd

End Function
 
use replace is very easy:
replace(&quot;John J. Van North&quot;, &quot; &quot;, &quot;&quot;)
replace(&quot;John J. Van North&quot;, &quot;.&quot;, &quot;&quot;)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top