Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zeros from a number in a string

Tags:

java

string

trim

I wanna trim this string.

"0000819780"

How i can get just the "819780" part.

I can do it with my way, just curious is there any "elegant" or "right" way to do this.

like image 592
Alamin Aji Avatar asked Apr 06 '16 03:04

Alamin Aji


5 Answers

I hope this works:

try {
   int i = Integer.parseInt(yourString);
   System.out.println(i);
} catch(NumberFormatException e) {
   // the string is not a number
}
like image 180
Aditya Jagtap Avatar answered Oct 18 '22 22:10

Aditya Jagtap


There are many ways you might remove leading zeros from your String; one approach, iterate the String from left to right stopping at the next to the last character (so you don't erase the final digit) stop if you encounter a non-zero and invoke String.substring(int) like

String str = "0000819780";
for (int i = 0, length = str.length() - 1; i < length; i++) {
    if (str.charAt(i) != '0') {
        str = str.substring(i);
        break;
    }
}
System.out.println(str);

Alternatively, parse the String like

int v = Integer.parseInt(str);
System.out.println(v);
like image 20
Elliott Frisch Avatar answered Oct 18 '22 22:10

Elliott Frisch


Alternative:

Using Apache Commons StringUtils class:

StringUtils.stripStart(String str, String stripChars);

For your example:

StringUtils.stripStart("0000819780", "0");  //should return "819780" 
like image 31
JosEduSol Avatar answered Oct 18 '22 21:10

JosEduSol


An elegant pure java way is just "0000819780".replaceFirst("^0+(?!$)", "")

like image 27
falcon Avatar answered Oct 18 '22 23:10

falcon


If the input is always a number and you want to remove only the beginning zeroes, just parse it into an integer. If you want it in string format, parse it back.

String a = "0000819780";
System.out.println(Long.parseLong(a));

Check https://ideone.com/7NMxbE for a running code.

If it can have values other than numbers, you would need to catch NumberFormatException

like image 28
Anindya Dutta Avatar answered Oct 18 '22 22:10

Anindya Dutta