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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Logic for Keeping chars (Not replace)?? 1

Status
Not open for further replies.

vbSun

Programmer
Dec 9, 2002
504
US
All,

I just bumped in to this and can't think of an optimal solution. Please give me some starting point.

We have the replace function which replaces char(s) from a string with something else. But in this case I need all the chars that I specify to be kept, everything else to be wiped off from the string. Obviously the replace function will work, if I can create a set which does not contain all the wanted chars, then loop through to remove them. But is there any other way you can think of to keep required chars and remove *ANY* other?

------------------------------------------
The faulty interface lies between the chair and the keyboard.
 
Create a project with a form, place 3 textboxes (txtSearchString, txtKeepChrs, txtResultString) and a button (btnKeep) on it and put the following code to the button's click event:
Code:
Private Sub btnKeep_Click()
Dim strSearch As String
Dim strKeep As String
Dim tmp As String
Dim chr As String * 1
Dim l As Long
Dim i As Long
  strSearch = txtSearchString.Text
  strKeep = txtKeepChrs.Text
  tmp = ""
  l = Len(strSearch)
  For i = 1 To l
    chr = Mid$(strSearch, i, 1)
    If InStr(1, strKeep, chr) <> 0 Then
      tmp = tmp & chr
    End If
  Next i
  txtResultString.Text = tmp
End Sub

Theophilos.

-----------

There are only 10 kinds of people: Those who understand binary and those who don't.
 
As strongm suggested, Regular Expressions are ideal for this problem. The Replace method in RegExp can replace characters that do not match your search, depending on how you supply the search pattern.
___
[tt]
Private Sub Form_Load()
'find all appearances of vowels in the string
MsgBox FilterString("Visual Basic", "aeiou")
Unload Me
End Sub

Function FilterString(Expression As String, FilterChars As String) As String
With CreateObject("VBScript.RegExp")
.IgnoreCase = True
.Global = True
.Pattern = "[^" & FilterChars & "]"
FilterString = .Replace(Expression, vbNullString)
End With
End Function[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top