假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
对我来说,使用范围操作符是最简单的方法。不需要太多代码。
在你的情况下,你可以得到你想要的:
// the ^ operator indicates the element position from the end of a sequence
string str = "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
下面是另一个应该不会太糟糕的替代方案(因为延迟执行):
新的字符串(mystring.Reverse (), (4) .Reverse () .ToArray ());
虽然mystring.Last(4)的扩展方法显然是最干净的解决方案,尽管要做更多的工作。
假设你想要一个距离最后一个字符10个字符的字符串之间的字符串,你只需要3个字符。
我们写入StreamSelected = "rtsp://72.142.0.230:80/ smile - chan -273/ 4cif -273.stream"
在上面,我需要提取我将在数据库查询中使用的“273”
//find the length of the string
int streamLen=StreamSelected.Length;
//now remove all characters except the last 10 characters
string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));
//extract the 3 characters using substring starting from index 0
//show Result is a TextBox (txtStreamSubs) with
txtStreamSubs.Text = streamLessTen.Substring(0, 3);
使用泛型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());
}
string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)