Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zero in Java

Tags:

java

string

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

like image 856
DataJ Avatar asked Aug 27 '15 15:08

DataJ


People also ask

How do you remove leading zeros in Java?

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.

How do you remove leading characters in Java?

You can use Apache StringUtils. stripStart to trim leading characters, or StringUtils. stripEnd to trim trailing characters.


2 Answers

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();
}
like image 158
Syam S Avatar answered Oct 04 '22 04:10

Syam S


  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");
}
like image 29
DwB Avatar answered Oct 04 '22 04:10

DwB