The disadvantage of using substring ()

What does this code do?

txtCardNo.Text.Trim().Substring((txtCardNo.Text.Trim().Length - 4), 4) 
+4
source share
2 answers

It gets the last 4 characters from txtCardNo (without leading or txtCardNo spaces), but it would be better if it were like this:

 var result = txtCardNo.Text.Trim(); result = result.Substring(result.Length - 4); 

EDIT:

Also note that this will result in an error if the cropped string has less than 4 characters. You could handle something like this:

 var result = txtCardNo.Text.Trim(); if (result.Length >=4) result = result.Substring(result.Length - 4); else // do domething 
+17
source

He gets the last four digits of the card number.

To break it:

 txtCardNo.Text = the contents of the Card Number textbox .Trim() = removes spaces from the end .Substring(x,y) = returns y characters from the string, starting at position x 

In this case, the x position is the length of the string minus 4, so we return the last four characters.

+3
source

All Articles