假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
这不仅仅是一个OP问题,而是一个如何将字符串的后3用于特定目的的例子。在我的例子中,我想对存储为字符串(1到3位数字)的数字字段进行数值排序(LINQ OrderBy)。所以,为了让字符串数字像数字一样排序,我需要用零填充字符串数字,然后取最后3。结果orderderby语句是:
myList = myList.OrderBy(x => string.Concat("00",x.Id)[^3..])
OrderBy语句中使用的string.Concat()会生成像“001”,“002”,“011”,“021”,“114”这样的字符串,如果它们被存储为数字,它们就会按照它们的方式排序。
其他回答
这对于任何长度的字符串都不会失败。
string mystring = "34234234d124";
string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
// last4 = "d124"
last4 = Regex.Match("d12", "(?!.{5}).*").Value;
// last4 = "d12"
对于当前的任务来说,这可能有些多余,但如果需要进行额外的验证,则可以将其添加到正则表达式中。
编辑:我认为这个正则表达式会更有效:
@".{4}\Z"
就是这样:
int count = 4;
string sub = mystring.Substring(mystring.Length - count, count);
更新2020:c# 8.0终于让这变得容易:
> "C# 8.0 finally makes this easy"[^4..]
"easy"
您还可以以相同的方式对数组进行切片,请参阅索引和范围。
与之前的一些答案相比,主要的区别是这段代码考虑了当输入字符串是:
零 大于或匹配所要求的长度 比要求的长度短。
下面就是:
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 mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)