Reputation: 19
I am using the substring function 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.
Upvotes: 0
Views: 2897
Reputation: 29116
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.
The first two characters of the string would be actnum.substring(0,2). The first argument is 0-based. The second argument is also 0-based, but is not included in the result.
Upvotes: 1
Reputation: 29680
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
Upvotes: 0
Reputation: 269637
The String.substring()
methods do not examine the content of the substring, so what you are describing is likely a bug in your code. You can post the minimal amount of code necessary to reproduce the problem if you'd like some help troubleshooting.
Given the code and information given in the update and comments, this is what I'd expect:
String actnum = "03KL352"; /* Maybe actnum is actually entered via a JSP. */
System.out.println(actnum); /* Prints 03KL352 */
String ccode = actnum.substring(1,2); /* Assign characters [1,2) to ccode. */
System.out.println(ccode); /* Prints 3 */
Remember, Java's string indexes are zero-based. The first character is at index 0, the next at index 1. Also, the substring
method takes two character indexes; the first is included in the new substring, the second is not—it is the index of the character after the last character in the new substring. So, the length of the new substring is end - start
.
Upvotes: 14