2014-07-16 136 views
0

我有一個帶有[bs]字符的文本文件。 [bs]表示退格。所以我想用退格替換[bs]。替換爲退格空字符串

Ex1: 
source text: 123[bs]45 
result must be :1245 

Ex2: 
source text: ABC DEF[bs][bs] GHI JKL[bs] 
result must be : ABC D GHI JK 
+0

一個簡單的循環可以做到這一點。沒有? – dotNET

+0

@dotNET你可以解釋一下代碼plz –

+0

添加我的答案。 – dotNET

回答

1

被修改爲 「[BS]」 規範:

Public Function ReplaceBackslashWithBackspace(ByVal inputText As String) As String 
    Dim replacementChar As Char = "#" ' ... or any character you are 100% you are not using in inputText 
    inputText = inputText.Replace("[bs]", replacementChar) 
    Dim outputStringBuilder As New Text.StringBuilder 
    For charIndex As Integer = 0 To inputText.Length - 1 
     If inputText(charIndex) = replacementChar Then 
      If outputStringBuilder.Length = 0 Then Continue For 
      outputStringBuilder.Length = outputStringBuilder.Length - 1 
     Else 
      outputStringBuilder.Append(inputText(charIndex)) 
     End If 
    Next 
    Return outputStringBuilder.ToString 
End Function 

測試:

Dim result As String = ReplaceBackslashWithBackspace("ABC DEF[bs][bs] GHI JKL[bs]") 
    ' result = "ABC D GHI JK" 
+0

他說Backspace,而不是反斜槓。 – dotNET

+0

你說得對,我的不好。編輯。雖然我不是100%確定'inputText(charIndex)= ControlChars.Back',也許你可以確認或編輯答案。 –

+0

你應該檢查'If'主體。 'x.Length = x.Length - 1'可能會引發異常。 – dotNET

-1
Private Function ReplaceBS(s As String) As String 
    Dim sb As New System.Text.StringBuilder(s.Length) 

    For i = 0 To s.Length - 1 
     If Convert.ToByte(s(i)) = 8 Then 
      If sb.Length > 0 Then sb.Remove(sb.Length - 1, 1) 
     Else 
      sb.Append(s(i)) 
     End If 
    Next 

    Return sb.ToString() 
End Function 
+0

'ReplaceBS' ...我認爲你是故意的。我喜歡它。 –

+0

對不起,它不起作用,因爲它不是退格字符。它是[bs]。 (有4個字符) –

+0

@JumRemdesk:你應該輸入[bs]爲「[bs]」,並明確地將其稱爲「字符串」[bs]「'。僅僅將它輸入爲[bs]會使大多數有經驗的用戶感到困惑,因爲括號[]用於表示佔位符和特殊字符。 – dotNET

0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Dim str, str1 As String 
str1 = "" 
str = "ABC DEF[bs][bs] GHI JKL[bs]" 
While InStr(str, "[bs]") <> 0 
str1 = str.Substring(str.IndexOf("[bs]") + 4) 
str = fun(str.Substring(0, str.IndexOf("[bs]"))) 
str = str & str1 
End While 
MsgBox(str)' will give the output 
End Sub 
Public Function fun(ByVal str As String) As String 
Return (str.Remove(str.Length - 1, 1)) 
End Function 
+0

仔細看看這個問題。這不是OP想要的。 – Jens

+0

這不會刪除以前的字符,因爲按'backspace'會。 – Grim

+0

讓我糾正它 – Suji

0

嘗試喜歡這張

Private Sub BSReplace(ByVal xst As String) 

     xstr = xstr.Replace(xstr.Substring(xstr.IndexOf("[") - 1, 5), String.Empty) 

     If xstr.Contains("[") Then Call BSReplace(xstr) Else MsgBox(xstr) 


End Sub 

call Call BSReplace("123[bs]45")