且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在C#中的字符串获得最后四个字符?

更新时间:2023-02-04 22:48:40

  mystring.Substring(Math.Max​​(0,mystring.Length  -  4));这//多少行是什么?

如果你是积极的字符串的长度至少是4,那么它更短:

  mystring.Substring(mystring.Length  -  4);

Suppose I have a string:

string mystring = "34234234d124";

I want to get the last four characters of this string which is "d124". I can use SubString, but it needs a couple of lines of code.

Is it possible to get this result in one expression with C#?

mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?

If you're positive the length of your string is at least 4, then it's even shorter:

mystring.Substring(mystring.Length - 4);