-1

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?

Saahon
  • 404
  • 1
  • 6
  • 27

3 Answers3

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