I want to delete some certain characters that used wrongly in a string.
"........I.wanna.delete.only.the.dots.outside.of.this.text..............."
as you can see I can't use replace for this. I must find a way to delete only the characters at left and right of a string and those dots only an example of characters that I want to delete. I have an array of those unwanted characters. So after the process string should look like
"I.wanna.delete.only.the.dots.outside.of.this.text"
but I couldn't find a way to get this work.
VB6 has a Trim()
function but that only removes spaces.
To remove characters from both ends, you'll need to check each end in turn removing the character until you get something else:
Function TrimChar(ByVal Text As String, ByVal Characters As String) As String
'Trim the right
Do While Right(Text, 1) Like "[" & Characters & "]"
Text = Left(Text, Len(Text) - 1)
Loop
'Trim the left
Do While Left(Text, 1) Like "[" & Characters & "]"
Text = Mid(Text, 2)
Loop
'Return the result
TrimChar = Text
End Function
Result:
?TrimChar("........I.wanna.delete.only.the.dots.outside.of.this.text...............", ".")
I.wanna.delete.only.the.dots.outside.of.this.text
This is far from optimised but you could expand on it to just work out the end positions, then do a single Mid()
call.
Public Function Remove(text As String) As String
text = Replace(text, "..", "")
If Left(text, 1) = "." Then
text = Right(text, Len(text) - 1)
End If
If Right(text, 1) = "." Then
text = Left(text, Len(text) - 1)
End If
Remove = text
End Function
If you remove any instances of ".." then you may or may not be left with a single leading dot and a single trailing dot to deal with. If you are lucky enough to be able to guarantee that the dots will always be an even number then
text = Replace(text, "..", "")
is all you need.