假设我有一个字符串:

"34234234d124"

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

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


当前回答

建议使用TakeLast方法,例如:new String(text.TakeLast(4).ToArray())

其他回答

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

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

它将返回结果0000。

建议使用TakeLast方法,例如:new String(text.TakeLast(4).ToArray())

一个简单的解决方案是:

string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);

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

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

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

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

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

mystring.Substring(mystring.Length - 4);