Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring() usage confusion

Tags:

string

c#

What does this code do?

txtCardNo.Text.Trim().Substring((txtCardNo.Text.Trim().Length - 4), 4)
like image 581
challengeAccepted Avatar asked Nov 30 '22 09:11

challengeAccepted


2 Answers

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

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

EDIT:

Also, note that this will throw error if trimmed string has less than 4 characters. You could handle it with something like this:

var result = txtCardNo.Text.Trim();
if (result.Length >=4)
   result = result.Substring(result.Length - 4);
else
   // do domething
like image 68
Ivan Ferić Avatar answered Dec 14 '22 23:12

Ivan Ferić


It's getting the last four digits of the card number.

To break it down:

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, position x is the length of the string minus 4, so we're returning the last four characters.

like image 33
Jacob Mattison Avatar answered Dec 15 '22 01:12

Jacob Mattison