Substring a string from the end of the string

前端 未结 9 956
别跟我提以往
别跟我提以往 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:46

    I will trim the end for unwanted characters:

    s = s.TrimEnd(' ', '!');
    

    To ensure it works even with more spaces. Or better if you want to ensure it works always, since the input text seems to come from the user:

    Regex r = new Regex(@"(?'purged'(\w|\s)+\w)");
    Match m = r.Match("Hello Marco   !!");
    if (m.Success)
    {
        string result = m.Groups["purged"].Value;
    }
    

    With this you are safer. A purge based on the fact the last two characters has to be removed is too weak.

    0 讨论(0)
  • 2020-12-16 11:47

    What about

    string s = "Hello Marco !";
    s = s.Substring(0, s.Length - 2);
    
    0 讨论(0)
  • 2020-12-16 11:48
    string s = "Hello Marco !";
    s = s.Remove(s.length - 2, 2);
    
    0 讨论(0)
  • 2020-12-16 11:54

    Try this:

    var s = "Hello Marco !";
    
    var corrected = s.Substring(0, s.Length - 2);
    
    0 讨论(0)
  • 2020-12-16 11:56

    C# 8 introduced indices and ranges which allow you to write

    str[^2..]
    

    This is equivalent to

    str.Substring(str.Length - 2, str.Length)
    

    In fact, this is almost exactly what the compiler will generate, so there's no overhead.

    Note that you will get an ArgumentOutOfRangeException if the range isn't within the string.

    0 讨论(0)
  • 2020-12-16 11:57
    s = s.Substring(0, Math.Max(0, s.Length - 2))
    

    to include the case where the length is less than 2

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