简体   繁体   中英

Remove leading zero in Java

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".

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();
}
  1. 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.
  2. 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).
  3. 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");
}

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
private String trimLeadingZeroes(inputStringWithZeroes){
    final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
    return trimZeroes.toString();
}

您可以使用下面的替换函数,它可以处理具有字母数字或数字的字符串

s.replaceFirst("^0+(?!$)", "")
public String removeLeadingZeros(String digits) {
    //String.format("%.0f", Double.parseDouble(digits)) //Alternate Solution
    String regex = "^0+";
    return digits.replaceAll(regex, "");
}

removeLeadingZeros("0123"); //Result -> 123
removeLeadingZeros("00000456"); //Result -> 456
removeLeadingZeros("000102030"); //Result -> 102030

You can use pattern matcher to check for strings with only zeros.

public static String removeLeadingZeroes(String value) {
    if (Pattern.matches("[0]+", value)) {
        return "0";
    } else {
        while (value.indexOf("0") == 0) {
            value = value.substring(1);
        }
        return value;
    }
}

You can try this:
1. If the numeric value of the string is 0 then return new String("0") .
2. Else remove the zeros from the string and return the substring .

public static String removeLeadingZeroes(String str)
{
    if(Double.parseDouble(str)==0)
        return new String("0");
    else
    {
        int i=0;
        for(i=0; i<str.length(); i++)
        {
            if(str.charAt(i)!='0')
                break;
        }
        return str.substring(i, str.length());
    }
}

Use String.replaceAll(), like this:

    public String replaceLeadingZeros(String s) {
        s = s.replaceAll("^[0]+", "");
        if (s.equals("")) {
            return "0";
        }

        return s;
    }

This will match all leading zeros (using regex ^[0]+) and replace them all with blanks. In the end if you're only left with a blank string, return "0" instead.

int n = 000012345;
n = Integer.valueOf(n + "", 10);

It is important to specify radix 10, else the integer is read as an octal literal and an incorrect value is returned.

public String removeLeadingZeros(String num) {
    String res = num.replaceAll("^0+", "").trim();
    return res.equals("")? "0" : res;
}
  1. Convert input to StringBuilder

  2. Use deleteCharAt method to remove character from beginning till non-zero character is found

    String trimZero(String str) { StringBuilder strB = new StringBuilder(str); int index = 0; while (strB.length() > 0 && strB.charAt(index) == '0') { strB.deleteCharAt(index); } return strB.toString(); }

I have found the following to be the simplest and most reliable, as it works for both integers and floating-point numbers:

public static String removeNonRequiredLeadingZeros(final String str) {
    return new BigDecimal(str).toPlainString();
}

You probably want to check the incoming string for null and blank, and also trim it to remove leading and trailing whitespace.

You can also get rid of trailing zeros by using:

public static String removeNonRequiredZeros(final String str) {
    return new BigDecimal(str).stripTrailingZeros().toPlainString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM