Rohan Meher
Rohan Meher

Reputation: 43

Replace leading zeros till decimal point with dash

If a string is a = 000102.45600. I need to convert it to a = ---102.45600. Any help in java using either regex or String formatter?

Tried the following:

a = a.replaceFirst("^0+(?!$)","-");

but i am getting only a = -102.45600 not 3 dashes.

Rules: Any leading zeros before decimal in string should be replaced by that many dashes.

  1. 000023.45677 to ----23.45677

  2. 002345.56776 to --2345.56776

  3. 00000.45678 to -----.45678

Hopefully I am clear on what my need is?

Upvotes: 3

Views: 437

Answers (3)

Bethany Louise
Bethany Louise

Reputation: 646

This should do it:

String number = //assign a value here
    for (int i=number.length();i>0; i--) {
        if (number.substring(0,i).matches("^0+$")) {
            System.out.println(number.replaceAll("0","-"));
            break;
        }
    }

This searches for the longest substring of number which starts at index 0 and consists entirely of zeroes - starting by checking the entire String, then shortening it until it finds the longest substring of leading zeroes. Once it finds this substring, it replaces each zero with a dash and breaks out of the loop.

Upvotes: 0

Wasi Ahmad
Wasi Ahmad

Reputation: 37691

String subjectString = "000102.45600";
String resultString = subjectString.replaceAll("\\G0", "-");
System.out.println(resultString); // prints ---102.45600

\G acts like \A (the start-of-string anchor) on the first iteration of replaceAll(), but on subsequent passes it anchors the match to the spot where the previous match ended. That prevents it from matching zeroes anywhere else in the string, like after the decimal point.

See: reference SO answer.

Upvotes: 4

older coder
older coder

Reputation: 704

Why not convert the start of the string to the "." to an integer, convert it back to a string then compare the lengths. 000102 length = 6. 102 length = 3. You would have your preceding zero count.

Upvotes: -2

Related Questions