tags:

views:

184

answers:

3

I am using the substring fuction in Java and what I am finding is if the first character in the substring is a zero, it is dropped from the new string. Is there a way to prevent this?

Here is the code I am having issues with:

ccode = actnum.substring(1,2);

Both ccode and actnum are defined as strings. If more code is needed, please advise.

+13  A: 
erickson
+1  A: 

Based on the code that you have in the question, you probably want the first two characters of the string. Assuming this to be the case, then the code that you want is:

ccode = actnum.substring(0,2);

The Javadoc for substring states that it returns the characters from the index specified by first argument up till, but not including, the index specified by the second argument.

Paul Wagland
A: 

Would be nice to have some example values...
but I suspect the problem is that you are only getting the second character of the String using
substring(1, 2)
the first parameter is the starting index (inclusive), the second the ending index (exclusive).

If you want the first and second character, you should use substring(0, 2).

It's worth consulting the documentation: String.substring

Carlos Heuberger