2014-07-16 101 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")