Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the last four characters from a string in C#?

Tags:

string

c#

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#?

like image 516
KentZhou Avatar asked Jun 20 '11 15:06

KentZhou


People also ask

How do you find the last 4 digits of a string?

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.

How do I get the last 5 characters of a string?

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.

How do I get the last 3 characters of a 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.


1 Answers

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); 
like image 71
Armen Tsirunyan Avatar answered Sep 24 '22 06:09

Armen Tsirunyan