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

halfer
  • 19,824
  • 17
  • 99
  • 186
DataJ
  • 153
  • 1
  • 1
  • 7
  • 6
    This thread should answer your question: http://stackoverflow.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text – alien01 Aug 27 '15 at 15:49
  • Add an `if` statement to look for that condition. (at the beginning of your `while` loop) – dsh Aug 27 '15 at 16:18

14 Answers14

37

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();
}
Syam S
  • 8,421
  • 1
  • 26
  • 36
16
  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");
}
DwB
  • 37,124
  • 11
  • 56
  • 82
  • 1
    Definitely the best answer. Experienced programmers use proven code whenever possible. The StringUtils answer is *much* better than the "untested but close" answer. – Tihamer Oct 08 '19 at 14:08
  • Exactly should be the best answer here, works like a charm. – Kevin STS Sep 07 '20 at 23:22
  • 1
    Not working for the "special case" from the question - this returns an empty string instead of "0". To make it work, you can replace `defaultString` with `defaultIfEmpty`. Relevant to the newest version of `commons-lang3` (3.11), probably it had been working in some older versions – amseager Dec 09 '20 at 09:21
  • But, I completely agree with the statements from the beginning of the answer. I would really like to see the first one somewhere on the main page of SO, and the second one - on the java tag page. – amseager Dec 09 '20 at 09:26
  • This is more complicated than, for example, "" + Integer.parseInt(origVal). It is true that the parseInt version can crash on non-numbers, but this is also sometimes what you want. The only time you want to add proven third party code in is if the proven code makes your solution simpler. It certainly is not going to be more reliable than language built-ins. – sf_jeff Aug 24 '22 at 20:34
  • Non exception version: "val = val.isNumber() ? "" + Integer.parseInt(val) : val". Note that for non-numbers, this differs from the solution above in that it assumes you don't want to trim 0s if it turns out to not be a number (more than 50% likely). – sf_jeff Aug 24 '22 at 20:46
2

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;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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
John C
  • 500
  • 3
  • 8
  • 1
    Using `if (s.matches("^0+$"))` would be much simpler. – TNT Aug 27 '15 at 15:53
  • Good point, but would want to use `"^0*$"` to satisfy the empty string case mentioned in "Should return "0" for input being "" or containing all zeroes," right? – John C Aug 27 '15 at 16:02
  • *"Given a valid, non-empty input"*? :P – TNT Aug 27 '15 at 17:09
  • /** * * Precondition: value is purely numeric * \@param value * \@return the value with leading zeroes removed. * **Should return "0" for input being ""** or containing all zeroes */ Can't seem to get the formatting right in the comment, but from the method documentation – John C Aug 27 '15 at 18:14
1
private String trimLeadingZeroes(inputStringWithZeroes){
    final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
    return trimZeroes.toString();
}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
  • Welcome to Stack Overflow! While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. [From review](https://stackoverflow.com/review/low-quality-posts/15057352) – Ferrybig Jan 31 '17 at 13:15
1

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

s.replaceFirst("^0+(?!$)", "")
Aman Systematix
  • 347
  • 2
  • 10
1
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
Ketan Ramani
  • 4,874
  • 37
  • 42
1
  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();
    }
    
ericdemo07
  • 461
  • 8
  • 16
0

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;
    }
}
Anand Kulkarni
  • 1,131
  • 1
  • 7
  • 7
  • It may works, but when I try to run your codes, Java says Pattern cannot be resolved. One more problem is I haven't learned "Pattern" yet, so probably not to use it :). – DataJ Aug 27 '15 at 23:07
  • @Claes Could you share more details of the error please. It's working fine for me. – Anand Kulkarni Aug 27 '15 at 23:42
0

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());
    }
}
anirban.at.web
  • 349
  • 2
  • 11
0

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.

tfarooqi
  • 49
  • 6
0
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.

mario
  • 51
  • 1
  • 3
0
public String removeLeadingZeros(String num) {
    String res = num.replaceAll("^0+", "").trim();
    return res.equals("")? "0" : res;
}
Cels
  • 1,212
  • 18
  • 25
0

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();
}
Rob Stoecklein
  • 749
  • 6
  • 9
  • 1
    You probably want toPlainString in the last one. Otherwise, 600.0 will become 6e2 in toString. – TT. Aug 10 '21 at 06:24