Suppose I have a string:
\"34234234d124\"
I want to get the last four characters of this string which is \"d124\"
. I can use <
It is just this:
int count = 4;
string sub = mystring.Substring(mystring.Length - count, count);
Using Substring is actually quite short and readable:
var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
// result == "d124"
Update 2020: C# 8.0 finally makes this easy:
> "C# 8.0 finally makes this easy"[^4..]
"easy"
You can also slice arrays in the same way, see Indices and ranges.
You can simply use Substring
method of C#. For ex.
string str = "1110000";
string lastFourDigits = str.Substring((str.Length - 4), 4);
It will return result 0000.
string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)
Compared to some previous answers, the main difference is that this piece of code takes into consideration when the input string is:
Here it is:
public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.Substring(str.Length - length, length);
}
public static string MyLast(this string str, int length)
{
if (str == null)
return null;
else if (str.Length >= length)
return str.Substring(str.Length - length, length);
else
return str;
}
}