how to insert last 5 characters of a string?

3

Hello, what happens is that I have a system in asp.net and c # in which the user must enter 15 numbers in a textbox, but only the last 5 of them must be saved in a database field. Nose if there is any SQL function to do that, or pass the last digits to a variable. I already inquired a little but I do not understand very well.

I found this code, but it marks me error

string cadena = codigo.Text;
string resultado = cadena.Substring(9, cadena.Length-4);
  

error: The index and length must refer to a location in the chain. Name of the parameter: length '

    
asked by Pikoh 05.05.2018 в 19:32
source

3 answers

3

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

    
answered by 07.05.2018 / 09:56
source
-2

I have been browsing the code but I think that if you only want to save the last 5 digits in the database what you can use is the String.Substring(int,int) method in which the two variables that you pass are:

-Index from where to start (in your case 10).

-Size of the chain (string.lenght-1).

All this before entering it in the database and with that you would get the last 5 digits of the chain or whatever you want. In this way I see that it can be easier.

    
answered by 05.05.2018 в 20:12
-4
  • Add Microsoft.VisualStudio to your references;
  • Using Microsoft.VisualStudio

  • Try with:

  • string stringOrigin="Hello World";

    string stringResult = Strings.Right (stringOrigin, 5);

    This will bring you as a result: "World"

    I hope it serves you.

        
    answered by 06.05.2018 в 17:28