Edit a string?

I would like to edit a string but I am having a little bit of trouble doing it.

For example:

string Mystring = "test\r\n";

I would like the string just to read "test".

how can i cut the last 4 chars off



Answer this question

Edit a string?

  • Ryan F

    Wes Payne wrote:

    Then Brendan Grant's suggestion is probably the best one. That way, trailing (and leading) whitespace characters, which can lead to unsightly boxes, will always get removed no matter how long the string you want to keep is.

    Hopefully, that's the worst you have to deal with. If there are other, special characters creeping in and leaving unsightly boxes, then sterner measures would be required.



    No I am only gathering the data from a stream and then posting it in a listbox control. So the Trim() method should work for what I need :D


  • gauthampj

    string myString = "test1234";

    myString = myString.Substring(0, myString.Length - 4);



  • BhuttCrackSpackle

    Try String's Trim() method which will remove any leading or trailing whitespace characters.

    MyString = MyString.Trim();



  • Apolodor

    In my case, Brandons answer has proved the most value. Thanks Brendon.

    Also Thanks cablehead for the alternative method, I have learned how to use substring too :D

    Wes thanks for the explanation of what the different types do.


  • CetinBasoz

    Then Brendan Grant's suggestion is probably the best one. That way, trailing (and leading) whitespace characters, which can lead to unsightly boxes, will always get removed no matter how long the string you want to keep is.

    Hopefully, that's the worst you have to deal with. If there are other, special characters creeping in and leaving unsightly boxes, then sterner measures would be required.


  • hrubesh

    I am only removing the "\r\n" because when you display it in a listbox, it comes up with a square and I dont want that square showing :D


  • Rab Lucas

    It really depends on why you want to edit it. If you're just trying to get rid of the trailing control characters (which, in this case, fall under the definition of 'whitespace'), then the first reply (using the .Trim() method) is the way to go.

    By the way, there are only two characters trailing "test". They are two control characters escaped out using the backslash. In this case, they're for moving the cursor to the beginning of the next line. So the second suggestion (trimming off the last four characters) will leave you with "te" instead of "test". If you just want the first four characters, regardless of what they are or what follows them, then use this code:

    string Newstring = Mystring.Substring(0, 4);

    Here, we're asking for the first four characters of Mystring, starting at index 0 (the very first character). The result would be "test".


  • Edit a string?