Substring a string from the end of the string

前端 未结 9 957
别跟我提以往
别跟我提以往 2020-12-16 11:16

I need to remove two characters from the end of the string.

So:

string = \"Hello Marco !\"

must be

Hello Marco


        
相关标签:
9条回答
  • 2020-12-16 11:59

    You can do:

    string str = "Hello Marco !";
    str = str.Substring(0, str.Length - 2);
    
    0 讨论(0)
  • 2020-12-16 12:03

    Did you check the MSDN documentation (or IntelliSense)? How about the String.Substring method?

    You can get the length using the Length property, subtract two from this, and return the substring from the beginning to 2 characters from the end. For example:

    string str = "Hello Marco !";
    str = str.Substring(0, str.Length - 2);
    
    0 讨论(0)
  • 2020-12-16 12:06

    If it's an unknown amount of strings you could trim off the last character by doing s = s.TrimEnd('','!').Trim();

    Have you considered using a regular expression? If you only want to allow alpha numeric characters you can use regex to replace the symbols, What if instead of a ! you get a %?

    0 讨论(0)
提交回复
热议问题