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

前端 未结 20 1079
陌清茗
陌清茗 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 19:01

    Use a generic Last. That will work with ANY IEnumerable, including string.

    public static IEnumerable Last(this IEnumerable enumerable, int nLastElements)
    {
        int count = Math.Min(enumerable.Count(), nLastElements);
        for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
        {
            yield return enumerable.ElementAt(i);
        }
    }
    

    And a specific one for string:

    public static string Right(this string str, int nLastElements)
    {
        return new string(str.Last(nLastElements).ToArray());
    }
    

提交回复
热议问题