假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
string var = "12345678";
var = var[^4..];
// var = "5678"
这是一个索引运算符,字面意思是“从end(^4)到end(..)取最后四个字符”
其他回答
假设你想要一个距离最后一个字符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);
mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?
如果你确定字符串的长度至少是4,那么它甚至更短:
mystring.Substring(mystring.Length - 4);
你所要做的就是…
String result = mystring.Substring(mystring.Length - 4);
一个简单的解决方案是:
string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);
这工作得很好,因为如果字符串中的字符比请求的数量少,也不会出现错误。
using System.Linq;
string.Concat("123".TakeLast(4));