public static String removeLeadingZeroes(String value):
Given a valid, non-empty input, the method should return the input with all leading zeroes removed. Thus, if the input is “0003605”, the method should return “3605”. As a special case, when the input contains only zeroes (such as “000” or “0000000”), the method should return “0”
public class NumberSystemService {
/**
*
* Precondition: value is purely numeric
* @param value
* @return the value with leading zeroes removed.
* Should return "0" for input being "" or containing all zeroes
*/
public static String removeLeadingZeroes(String value) {
while (value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I don't know how to write codes for a string "0000".
Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.
You can use Apache StringUtils. stripStart to trim leading characters, or StringUtils. stripEnd to trim trailing characters.
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();
}
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With