假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
你可以简单地使用c#的Substring方法。前女友。
string str = "1110000";
string lastFourDigits = str.Substring((str.Length - 4), 4);
它将返回结果0000。
其他回答
对我来说,使用范围操作符是最简单的方法。不需要太多代码。
在你的情况下,你可以得到你想要的:
// the ^ operator indicates the element position from the end of a sequence
string str = "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);
这工作得很好,因为如果字符串中的字符比请求的数量少,也不会出现错误。
using System.Linq;
string.Concat("123".TakeLast(4));
更新2020:c# 8.0终于让这变得容易:
> "C# 8.0 finally makes this easy"[^4..]
"easy"
您还可以以相同的方式对数组进行切片,请参阅索引和范围。
这不仅仅是一个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”这样的字符串,如果它们被存储为数字,它们就会按照它们的方式排序。