I have a string "00000000800540"
. Always identical length of string. But can change the number of zeros to 8. Instead, 8 can also another number. How to get me the number 800540 from the string?
Asked
Active
Viewed 331 times
-1

Saahon
- 404
- 1
- 6
- 27
-
do you want to strip all left padded `0` ? – Sanjeev Apr 27 '16 at 07:31
-
Yes you can. Share what you have tried out – sidgate Apr 27 '16 at 07:31
-
@Sanjeev Yes exactly!!!! – Saahon Apr 27 '16 at 07:32
-
2Here's a silly way: `Long.valueOf(str).toString()` – shmosel Apr 27 '16 at 07:33
3 Answers
1
You can use this:
givenNumberAsString.replaceFirst("^0+(?!$)", "")
This will work no matter how long your string is.

Adnan Isajbegovic
- 2,227
- 17
- 27
1
A non-regex way:
int i = 0;
while (i < str.length() && str.charAt(i) == '0') ++i;
String withoutLeadingZeros = str.substring(i);
This will trim all zeros, even if the string is all zeros. If you want to preserve the last zero in this case, change the while loop guard to:
i + 1 < str.length() && str.charAt(i) == '0'

Andy Turner
- 137,514
- 11
- 162
- 243
-
-
@shmosel noted, and added a modification to handle this if required. – Andy Turner Apr 27 '16 at 09:30
0
Depending on the length of the expected number contained in string, you can use Integer.parseInt(**string**)
or Long.parseLong(**string**)
.
String st = "00000000800540";
System.out.println(Long.parseLong(st)); // 800540
System.out.println(Integer.parseInt(st)); // 800540

Debosmit Ray
- 5,228
- 2
- 27
- 43