-
Is there a way to remove certain words from strings.
Say the user enters "I have a dog and his name is Rover" in the text box, can I set it up so the program removes the words "dog" and "rover"
Also, can this be done using integers, so that say i have an integer "139547" and I want to remove the last 3 digits, and print the other numbers in a textbox, how would i go about doing this.
I am using VB4.0 if it matters.
-
Using the mid() you would do it like this...
Mid(<string>,<position of first letter>,<length of string> )
cString = "I have a dog named rover"
cFirstString = Mid(cString,10,3) '= dog
cSecondString = Mid(cString,20,5) '= rover
You can also concatinate the string back together without those parts like this.
cNewString = Mid(cString,1,9) & Mid(cString,13,6)
'cNewString = "I have a named"
-
If you don't where the word you want to extract is but you know what your looking for you can search for it like this.
dim nPos as integer
For nPos = 1 to (Len(cString) - 3)
if Mid(cString,nPos,3) = "dog" then
'remove it as shown above
end if
Next
-
Same goes for integers but you will have to change the type before comparing them as a string.
You can do this using...
cString = CStr(nInt) 'Returns a string representation of an integer
-
scuzymoto: Any value in a string even if it's just numbers is by definition a string already, so you don't need to convert it.
-
Use the Replace Function. Since you have VB4, use the function below to simulate the Replace function.
Code:
Public Function Replace(sIn As String, sFind As String, _
sReplace As String, Optional nStart As Long = 1, _
Optional nCount As Long = -1, Optional bCompare As _
VbCompareMethod = vbBinaryCompare) As String
Dim nC As Long, nPos As Integer, sOut As String
sOut = sIn
nPos = InStr(nStart, sOut, sFind, bCompare)
If nPos = 0 Then GoTo EndFn:
Do
nC = nC + 1
sOut = Left(sOut, nPos - 1) & sReplace & _
Mid(sOut, nPos + Len(sFind))
If nCount <> -1 And nC >= nCount Then Exit Do
nPos = InStr(nStart, sOut, sFind, bCompare)
Loop While nPos > 0
EndFn:
Replace = sOut
End Function
Now make a CommandButton and put in the following code to use it. Make sure that there is a TextBox on the Form. Keep the name as Text1.
Code:
Private Sub Command1_Click()
rv = Replace(Text1.Text, "hello", "bye")
Text1 = rv
End Sub
-
Thanks everyone. It worked great!
Now I know a little more about VB :)