假设我有一个字符串:

"34234234d124"

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

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


当前回答

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

其他回答

下面是另一个应该不会太糟糕的替代方案(因为延迟执行):

新的字符串(mystring.Reverse (), (4) .Reverse () .ToArray ());

虽然mystring.Last(4)的扩展方法显然是最干净的解决方案,尽管要做更多的工作。

定义:

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

用法:

GetLast("string of", 2);

结果:

of

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

using System.Linq;

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

与之前的一些答案相比,主要的区别是这段代码考虑了当输入字符串是:

零 大于或匹配所要求的长度 比要求的长度短。

下面就是:

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;
    }
}

对我来说,使用范围操作符是最简单的方法。不需要太多代码。

在你的情况下,你可以得到你想要的:

// the ^ operator indicates the element position from the end of a sequence
string str = "34234234d124"[^4..]