Suppose I have a string:
"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, including naming a variable.
Is it possible to get this result in one expression with C#?
To get the last 4 digits of a number:Convert the number to a string and call the slice() method on the string, passing it -4 as a parameter. The slice method will return the last 4 character in the string. Convert the string back to a number to get the 4 last digits.
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string.
To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method. so it begins the extraction at index position s.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With