DataJ
DataJ

Reputation: 153

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

Upvotes: 13

Views: 57067

Answers (14)

Rob Stoecklein
Rob Stoecklein

Reputation: 989

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();
}

Upvotes: 0

ericdemo07
ericdemo07

Reputation: 481

  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();
    }
    

Upvotes: 0

Cels
Cels

Reputation: 1334

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

Upvotes: 0

DwB
DwB

Reputation: 38300

  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");
}

Upvotes: 17

mario
mario

Reputation: 69

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.

Upvotes: 0

Ketan Ramani
Ketan Ramani

Reputation: 5753

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

Upvotes: 1

Aman Systematix
Aman Systematix

Reputation: 347

You can use below replace function it will work on a string having both alphanumeric or numeric

s.replaceFirst("^0+(?!$)", "")

Upvotes: 1

tfarooqi
tfarooqi

Reputation: 69

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.

Upvotes: 0

Samarth Urs
Samarth Urs

Reputation: 11

private String trimLeadingZeroes(inputStringWithZeroes){
    final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
    return trimZeroes.toString();
}

Upvotes: 1

anirban.at.web
anirban.at.web

Reputation: 359

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());
    }
}

Upvotes: 0

Anand Kulkarni
Anand Kulkarni

Reputation: 1201

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;
    }
}

Upvotes: 0

John C
John C

Reputation: 501

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

Upvotes: 1

Syam S
Syam S

Reputation: 8499

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();
}

Upvotes: 37

Mureinik
Mureinik

Reputation: 311143

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;
}

Upvotes: 2

Related Questions