CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 23

Threaded View

  1. #1
    Join Date
    Jun 2004
    Location
    NH
    Posts
    678

    Quirk String.Remove vs StringBuilder.Remove

    I found a quirk that may be helpful for someone else to know, if they run into the same mistake.
    EDIT: By quirk, I mean that a newbie may not be able to predict the behavior, thus causing them to make a mistake.


    You can remove part of a string "In place" by using the StringBuilder.Remove method.
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim sb As New System.Text.StringBuilder("randomstring2342")
    
            sb.Remove(0, 6)
    
            MessageBox.Show(sb.ToString)
        End Sub
    However, you can not remove it "In place", if you are using String.Remove.
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim s As String = "randomstring2342"
    
            s.Remove(0, 6)
    
            MessageBox.Show(s)
        End Sub
    You have to use the return value instead.
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim s As String = "randomstring2342"
    
            s = s.Remove(0, 6)
    
            MessageBox.Show(s)
        End Sub

    Although, the stringbuilder allows you to use the return value too.
    One might not expect that you'd be able to set it "In place" or by it's "Return value".
    You may expect that a String can be set in place though.
    Last edited by TT(n); March 26th, 2009 at 11:00 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured