Substring

  • Thread starter Thread starter Mike P
  • Start date Start date
M

Mike P

If I want to get the last 4 characters of a string is this the right way
to do it?

int intCardLength = Convert.ToInt32(strCardNumberUnEnc.Length);
strCardNumberUnEnc = strCardNumberUnEnc.Substring(intCardLength -
4, 4);

Or is there stuff (Length, Substring) that is zero-indexed that will
mean I need to take account of?
 
Just use it like this:
string abc = "abcdefghijklmnopqrstuvwxyz";
string abcEnd = abc.Substring(abc.Length - 4);

Hope I understood your question right...

Greetings,
timtos.
 
Mike,

As a general rule, when dealing with anything in .NET/C#, everything
runs off a zero-based index (there are probably exceptions, but for the most
part, this is true).

The Substring method is the same. So, if you want to get the last four
characters, you can do this:

strCardNumberUnEnc =
strCardNumberUnEnc.Substring(strCardNumberUnEnc.Length - 4, 4);

Which is basically what you had. You don't need the call to convert,
since the Length property returns an int.

Hope this helps.
 
Back
Top