假设我有一个字符串:

"34234234d124"

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

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


当前回答

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

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

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

其他回答

string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)
string var = "12345678";

if (var.Length >= 4)
{
    var = var.substring(var.Length - 4, 4)
}

// result = "5678"

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

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

using Microsoft.VisualBasic;
//...

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

定义:

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

用法:

GetLast("string of", 2);

结果:

of

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

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

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