假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
与之前的一些答案相比,主要的区别是这段代码考虑了当输入字符串是:
零 大于或匹配所要求的长度 比要求的长度短。
下面就是:
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;
}
}
其他回答
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);
假设你想要一个距离最后一个字符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);
建议使用TakeLast方法,例如:new String(text.TakeLast(4).ToArray())
下面是另一个应该不会太糟糕的替代方案(因为延迟执行):
新的字符串(mystring.Reverse (), (4) .Reverse () .ToArray ());
虽然mystring.Last(4)的扩展方法显然是最干净的解决方案,尽管要做更多的工作。