假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
string var = "12345678";
var = var[^4..];
// var = "5678"
这是一个索引运算符,字面意思是“从end(^4)到end(..)取最后四个字符”
其他回答
你可以使用扩展方法:
public static class StringExtension
{
public static string GetLast(this string source, int tail_length)
{
if(tail_length >= source.Length)
return source;
return source.Substring(source.Length - tail_length);
}
}
然后调用:
string mystring = "34234234d124";
string res = mystring.GetLast(4);
这工作得很好,因为如果字符串中的字符比请求的数量少,也不会出现错误。
using System.Linq;
string.Concat("123".TakeLast(4));
public static string Last(this string source, int tailLength)
{
return tailLength >= source.Length ? source : source[^tailLength..];
}
对我来说,使用范围操作符是最简单的方法。不需要太多代码。
在你的情况下,你可以得到你想要的:
// the ^ operator indicates the element position from the end of a sequence
string str = "34234234d124"[^4..]
使用泛型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());
}