Remove leading zero in Java
- Stop reinventing the wheel. Almost no software development problem you ever encounter will be the first time it has been encountered; instead, it will only be the first time you encounter it.
- Almost every utility method you will ever need has already been written by the Apache project and/or the guava project (or some similar that I have not encountered).
- Read the Apache StringUtils JavaDoc page. This utility is likely to already provide every string manipulation functionality you will ever need.
Some example code to solve your problem:
public String stripLeadingZeros(final String data)
{
final String strippedData;
strippedData = StringUtils.stripStart(data, "0");
return StringUtils.defaultString(strippedData, "0");
}
If the string always contains a valid integer the return new Integer(value).toString();
is the easiest.
public static String removeLeadingZeroes(String value) {
return new Integer(value).toString();
}
You could add a check on the string's length:
public static String removeLeadingZeroes(String value) {
while (value.length() > 1 && value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I would consider checking for that case first. Loop through the string character by character checking for a non "0" character. If you see a non "0" character use the process you have. If you don't, return "0". Here's how I would do it (untested, but close)
boolean allZero = true;
for (int i=0;i<value.length() && allZero;i++)
{
if (value.charAt(i)!='0')
allZero = false;
}
if (allZero)
return "0"
...The code you already have