[GIS] replace character in string in mapbasic

mapbasic

Is there an equivalent to python .replace in mapbasic? Something like

search = search.replace(',', ' ')

I have found the search and replace tool for mapinfo and it works well but I need something simple to just replace all the ',' in a table with a space.

There are questions from 2007 saying this is not possible but has this changed? http://git.net/ml/mapinfo-l/2009-09/msg00107.html and https://groups.google.com/forum/#!topic/mapinfo-l/9QLqjsBTO_0

From one of my past questions I see we can find the ',' using

(InStr(1, SearchColumn, ",")

but how do I replace this character when found?

A line would be like "123, Main Street, GIS Town" and should become "123 Main Street GIS Town"

and it needs to be run in a table update command.

Update DCDB_Address Set Search = Search+" [Address]"

Best Answer

Unfortunately, there is no built in 'search & replace' functionality in the MapBasic language. The way I've always done this is to use a custom function and include this in any projects where I've needed to search/replace.

My search and replace function takes a string as input and returns a string as output, so you could use this in an update query.

e.g. UPDATE myTable SET myTextField = SearchReplace(myTextField, ",", " ")

Here's the function:

'=========================================
'// <summary>
'// Replace part of a string with another string
'// </summary>
'-----------------------------------------
Function SearchReplace(ByVal strInput as String, ByVal strReplace as String, ByVal strReplacement as String) as String

Dim iPos as Integer
Dim strOut as String
Dim i as Integer

    iPos = InStr(1, strInput, strReplace)
    If iPos < 1 then            '// nothing to replace, return original string
        SearchReplace = strInput
        Exit Function
    End If

    While iPos > 0              '// loop until nothing left to replace
        If iPos > 1 then
            strOut = Left$(strInput, iPos - 1)
        End if
        strOut = strOut & strReplacement
        If iPos + Len(strReplace) - 1 < Len(strInput) then
            strOut = strOut & Mid$(strInput, iPos + Len(strReplace), Len(strInput) - (iPos + Len(strReplace)) + 1)
        End If

        strInput = strOut
        iPos = InStr(iPos + 1, strInput, strReplace)
    Wend

    SearchReplace = strOut

End Function
Related Question