[GIS] Removing non-alphanumeric characters from string in MapBasic

mapbasicmapinfo

I have a user-entered string which I am using as a search term. I would like to display the results in a table named "SearchResults_"+SearchString. However the string could feasibly contain characters that can't be used for table names – spaces would be the most common and there are plenty of other strange characters in place names.

I would like to strip all special, non-alphanumeric characters from a string.

As far as I can see there aren't any built-in functions that would achieve this.

I can loop through the characters easily enough but comparing each one to a white-list is proving harder than I expected. I could do it with a epic if/else statement but that's just dirty! VB.net has IsLetterOrDigit() which would be nice. PHP has ctype_alnum(). In Python I'd just check it against a white-list string.

Any ideas?

Best Answer

Well that wasn't so hard.

Declare Sub Main
Declare Function RemoveSpecialChars(byval str as string) as String

Sub Main
    Dim t as string
    t = "this is a string with spaces and ' ! * & ^ % $ £ punctuation"

    Print Chr$(12) + "Original String: " + t
    Print "Tidy string: " + RemoveSpecialChars(t)

    End Program
End Sub

Function RemoveSpecialChars(byval str as string) as String
    Dim chr, out, nicechars as String
    Dim i, l as Integer

    nicechars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    l = Len(str)

    For i = 1 to l
        chr = Mid$(str, i, 1)
        If InStr(1, nicechars, chr) > 0 Then
            out = out + chr
        End If
    Next

    RemoveSpecialChars = out
End Function
Related Question