You can use LINQ
methods to get the n
last characters of a string
. For this, a very simple option is to use Reverse
and Take
. Basically, we return the string, we get 5 characters and we turn them over again:
var resultado=new string(cadena.Reverse().Take(5).Reverse().ToArray());
This also has an advantage: if there are less than 5 characters in the string, it will not throw an exception, it will simply return the characters that exist.
Anyway, it would not hurt to check if the length of the chain is at least 5 and otherwise return for example an empty string. Something like this:
var resultado=cadena.Length>=5?new string(cadena.Reverse().Take(5).Reverse().ToArray()):"";
P.D. The problem with your code as you have been indicated is that the second parameter of String.Substring
is the number of characters you want to pick up. As in your case it is always 5, you can put it directly: cadena.Substring(10,5)
. Since they are always the last, you can omit the last parameter: cadena.Substring(10)
. Or, if you want to get the last 5 characters whatever the size of the original string: cadena.Substring(cadena.Length-5)
. Keep in mind in all these cases that you have to make sure that the size of the original string is right or you will receive an error like the one you are having right now of type System.ArgumentOutOfRangeException