Remove a Character from a String

This function will search for a specific character in a text string and remove the specified character when it is found.

How It Works

A text string and search string are passed to the function. The function loops through each character in the text string and compares each character with the specified search string. If the two values do not match, the current character is added to a temporary string. The loop is then incremented, and the next character is checked. If the values match, the current character is not added to the temporary array. After all characters are checked, the temporary string is returned to the calling code with all instances of the search string removed.

Implementation

This function requires two parametersa text string and the target character to be removed by the text search string.

Function RemoveString ( TextString As String, SearchString As String ) Dim tempString As String Dim currChar As String Dim x As Integer tempString = "" For x = 1 To Len( TextString ) currChar = Mid$( textString, x, 1 ) If currChar <> SearchString Then tempString = tempString + currChar End If Next RemoveString = tempString End Function

The following illustrates how this function could be called from an action button. In this example, the character "B" is removed from the text string "ABCD" (see Figure 13.2). The revised text string, "ACD", is subsequently stored in the MyOutput string.

Sub Click(Source As Button) Dim MyOutput As String Msgbox "ABCD", , "Original String" MyOutput = RemoveString ( "ABCD", "B" ) Msgbox MyOutput, , "Replaced String" End Sub

Figure 13.2. Remove a character from a string

Категории