Deleting certain character from right and left of a string in vb6 (TrimChar)

吃可爱长大的小学妹 提交于 2020-01-13 11:11:09

问题


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.


回答1:


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.




回答2:


    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.



来源:https://stackoverflow.com/questions/8531543/deleting-certain-character-from-right-and-left-of-a-string-in-vb6-trimchar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!