How do I get the last four characters from a string in C#?

前端 未结 20 1060
陌清茗
陌清茗 2020-11-30 18:13

Suppose I have a string:

\"34234234d124\"

I want to get the last four characters of this string which is \"d124\". I can use <

相关标签:
20条回答
  • 2020-11-30 18:42

    It is just this:

    int count = 4;
    string sub = mystring.Substring(mystring.Length - count, count);
    
    0 讨论(0)
  • 2020-11-30 18:43

    Using Substring is actually quite short and readable:

     var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
     // result == "d124"
    
    0 讨论(0)
  • 2020-11-30 18:43

    Update 2020: C# 8.0 finally makes this easy:

    > "C# 8.0 finally makes this easy"[^4..]
    "easy"
    

    You can also slice arrays in the same way, see Indices and ranges.

    0 讨论(0)
  • 2020-11-30 18:46

    You can simply use Substring method of C#. For ex.

    string str = "1110000";
    string lastFourDigits = str.Substring((str.Length - 4), 4);
    

    It will return result 0000.

    0 讨论(0)
  • 2020-11-30 18:47
    string mystring = "34234234d124";
    mystring = mystring.Substring(mystring.Length-4)
    
    0 讨论(0)
  • 2020-11-30 18:47

    Compared to some previous answers, the main difference is that this piece of code takes into consideration when the input string is:

    1. Null
    2. Longer than or matching the requested length
    3. Shorter than the requested length.

    Here it is:

    public static class StringExtensions
    {
        public static string Right(this string str, int length)
        {
            return str.Substring(str.Length - length, length);
        }
    
        public static string MyLast(this string str, int length)
        {
            if (str == null)
                return null;
            else if (str.Length >= length)
                return str.Substring(str.Length - length, length);
            else
                return str;
        }
    }
    
    0 讨论(0)
提交回复
热议问题