替换为退格空字符串

时间:2014-07-16 09:11:13

标签: vb.net

我有一个带[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

4 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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

答案 2 :(得分: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") 

答案 3 :(得分:-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