假设我有一个字符串:

"34234234d124"

我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。

是否有可能在c#的一个表达式中得到这个结果?


当前回答

这工作得很好,因为如果字符串中的字符比请求的数量少,也不会出现错误。

using System.Linq;

string.Concat("123".TakeLast(4));

其他回答

mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;
mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?

如果你确定字符串的长度至少是4,那么它甚至更短:

mystring.Substring(mystring.Length - 4);
public static string Last(this string source, int tailLength)
{
  return tailLength >= source.Length ? source : source[^tailLength..];
}

使用Substring实际上是非常简短和可读的:

 var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
 // result == "d124"

使用泛型Last<T>。这将适用于任何IEnumerable,包括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);
    }
}

和string的一个特定的:

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