Remove leading zero in Java

public static String removeLeadingZeroes(String value): 

Given a valid, non-empty input, the method should return an input with all leading zeros. Thus, if the input is "0003605", the method should return "3605". As a special case, when the input contains only zeros (for example, "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 do not know how to write codes for the string "0000".

+5
source share
7 answers

I would consider checking this case first. Scroll through the string character with a character check for the character "0". If you see the character "0", use the process that you have. If you do not, 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 
+1
source

If the string always contains a valid integer, then return new Integer(value).toString(); is the easiest.

 public static String removeLeadingZeroes(String value) { return new Integer(value).toString(); } 
+24
source

You can add a string length check:

 public static String removeLeadingZeroes(String value) { while (value.length() > 1 && value.indexOf("0")==0) value = value.substring(1); return value; } 
+1
source
 private String trimLeadingZeroes(inputStringWithZeroes){ final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes); return trimZeroes.toString(); } 
+1
source

You can use a template pattern to check 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; } } 
0
source

You can try the following:
1. If the numeric value of the string is 0, then return a new string ("0") .
2. Otherwise, remove 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()); } } 
0
source

Use String.replaceAll (), for example:

  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 with spaces. In the end, if you are left with only an empty string, return "0".

0
source

All Articles