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

前端 未结 20 1063
陌清茗
陌清茗 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:59

    Suggest using TakeLast method, for example: new String(text.TakeLast(4).ToArray())

    0 讨论(0)
  • This won't fail for any length string.

    string mystring = "34234234d124";
    string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
    // last4 = "d124"
    last4 = Regex.Match("d12", "(?!.{5}).*").Value;
    // last4 = "d12"
    

    This is probably overkill for the task at hand, but if there needs to be additional validation, it can possibly be added to the regular expression.

    Edit: I think this regex would be more efficient:

    @".{4}\Z"
    
    0 讨论(0)
  • 2020-11-30 19:01

    Definition:

    public static string GetLast(string source, int last)
    {
         return last >= source.Length ? source : source.Substring(source.Length - last);
    }
    

    Usage:

    GetLast("string of", 2);
    

    Result:

    of

    0 讨论(0)
  • 2020-11-30 19:01

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

    public static IEnumerable<T> Last<T>(this IEnumerable<T> 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());
    }
    
    0 讨论(0)
  • 2020-11-30 19:02

    You can use an extension method:

    public static class StringExtension
    {
        public static string GetLast(this string source, int tail_length)
        {
           if(tail_length >= source.Length)
              return source;
           return source.Substring(source.Length - tail_length);
        }
    }
    

    And then call:

    string mystring = "34234234d124";
    string res = mystring.GetLast(4);
    
    0 讨论(0)
  • 2020-11-30 19:02

    A simple solution would be:

    string mystring = "34234234d124";
    string last4 = mystring.Substring(mystring.Length - 4, 4);
    
    0 讨论(0)
提交回复
热议问题