Search code examples
vb.netreplacestringbuilder

AppendLine and replacing


I want to get my output from

223-F456

to

223-F456

223-F456#

223-F4560

223-#456

I've done simple code for this but only adding #,0 to the ends of lines works:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim sb As New StringBuilder
        For Each line In TextBox1.Lines
            sb.AppendLine(line)
            sb.AppendLine(line & "#")
            sb.AppendLine(line & "0")
            sb.Replace(line.LastIndexOf("-") + 1, "#") -> this doesn't work 
        Next
        TextBox2.Text = sb.ToString

output:

223-F456

223-F456#

223-F4560

The letter is not always "F": I want to replace first letter after "-" not replace "F", also might some serials have "F" letter that not what I want.

Simple products serial in shop but replacing the string after "-" doesn't work and doesn't show, any help would be appreciated.


Solution

  • You can use String.Remove and String.Insert like this:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim sb As New StringBuilder()
    
        For Each line In TextBox1.Lines
            sb.AppendLine(line)
            sb.AppendLine(line & "#")
            sb.AppendLine(line & "0")
            Dim replaceAt = line.LastIndexOf("-") + 1
            sb.AppendLine(line.Remove(replaceAt, 1).Insert(replaceAt, "#"))
        Next
    
        TextBox2.Text = sb.ToString()
    
    End Sub
    

    Or if you preferred then you could use the String.Substring function:

        sb.AppendLine(line.Substring(0, replaceAt) & "#" & line.Substring(replaceAt + 1))
    

    It would also be possible to use a regular expression to do the replace, I expect someone else could come up with a better regex, but this works:

        Dim re As New Regex("(.*-)([^-])(.*)")
        For Each line In TextBox1.Lines
            ' ...
            sb.AppendLine(re.Replace(line, "$1#$3"))