2011-12-16 55 views
3

我想刪除字符串中錯誤使用的某些字符。從vb6中的字符串的右側和左側刪除某個字符(TrimChar)

「........ I.wanna.delete.only.the.dots.out.of.this.text ...............」

你可以看到我不能使用替換這個。我必須找到一種方法來只刪除字符串左側和右側的字符,而這些點只是我想要刪除的字符的一個示例。我有一些不需要的字符。因此,處理後的字符串應該像

「I.wanna.delete.only.the.dots.outside.of.this.text」

,但我無法找到一個方法來得到這個工作。

回答

11

VB6具有Trim()函數,但僅刪除空格。

從兩端刪除字符,你需要檢查每端依次去掉字符,直到你得到別的東西:

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 

結果:

?TrimChar("........I.wanna.delete.only.the.dots.outside.of.this.text...............", ".") 
I.wanna.delete.only.the.dots.outside.of.this.text 

這遠遠優化,但你可以擴大到最終職位,然後做一個Mid()電話。

1
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 

如果你刪除的任何實例「」那麼你可能會或可能不會留下一個單一的領先點和一個結尾點來處理。如果你足夠幸運能夠保證點總是偶數,那麼

text = Replace(text, "..", "") 

是你所需要的。

+1

你如何獲得`Replace()`來區分。你想保持和。你不?他們不能代替字符串的整個「保留」部分,直到他們知道它是什麼(這是他們要求的) – Deanna 2011-12-16 10:01:46

相關問題