假设我有一个字符串:

"34234234d124"

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

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


当前回答

使用泛型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());
}

其他回答

更新2020:c# 8.0终于让这变得容易:

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

您还可以以相同的方式对数组进行切片,请参阅索引和范围。

你可以简单地使用c#的Substring方法。前女友。

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

它将返回结果0000。

好吧,我知道这是一篇旧文章,但为什么我们要重写框架中已经提供的代码呢?

我建议您添加一个对框架DLL "Microsoft. DLL "的引用。VisualBasic”

using Microsoft.VisualBasic;
//...

string value = Strings.Right("34234234d124", 4);
string var = "12345678";

var = var[^4..];

// var = "5678"

这是一个索引运算符,字面意思是“从end(^4)到end(..)取最后四个字符”

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

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