假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
使用Substring实际上是非常简短和可读的:
var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
// result == "d124"
其他回答
就是这样:
int count = 4;
string sub = mystring.Substring(mystring.Length - count, count);
更新2020:c# 8.0终于让这变得容易:
> "C# 8.0 finally makes this easy"[^4..]
"easy"
您还可以以相同的方式对数组进行切片,请参阅索引和范围。
这对于任何长度的字符串都不会失败。
string mystring = "34234234d124";
string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
// last4 = "d124"
last4 = Regex.Match("d12", "(?!.{5}).*").Value;
// last4 = "d12"
对于当前的任务来说,这可能有些多余,但如果需要进行额外的验证,则可以将其添加到正则表达式中。
编辑:我认为这个正则表达式会更有效:
@".{4}\Z"
假设你想要一个距离最后一个字符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);
好吧,我知道这是一篇旧文章,但为什么我们要重写框架中已经提供的代码呢?
我建议您添加一个对框架DLL "Microsoft. DLL "的引用。VisualBasic”
using Microsoft.VisualBasic;
//...
string value = Strings.Right("34234234d124", 4);