How to extract the digits of a floating-point number before and after the decimal point from a string in Java

1 Answer

0 votes
public class ExtractFloatDigits {

    /**
        extractFloatDigits
        -------------------
        Scans the input string and extracts the digits before and after
        the decimal point of the first floating‑point number found.

        Steps:
          1. Find the first digit.
          2. Collect digits until a decimal point.
          3. After '.', collect digits again.
          4. Stop when a non‑digit is encountered.

        This approach avoids regex overhead and uses efficient
        character scanning.
    */
    public static void extractFloatDigits(String s,
                                          StringBuilder before,
                                          StringBuilder after) {

        before.setLength(0);
        after.setLength(0);

        int i = 0;
        int n = s.length();

        // Step 1: Find the first digit
        while (i < n && !Character.isDigit(s.charAt(i))) {
            i++;
        }

        // Step 2: Collect digits before the decimal point
        while (i < n && Character.isDigit(s.charAt(i))) {
            before.append(s.charAt(i));
            i++;
        }

        // Step 3: Check for decimal point
        if (i < n && s.charAt(i) == '.') {
            i++; // skip '.'

            // Step 4: Collect digits after the decimal point
            while (i < n && Character.isDigit(s.charAt(i))) {
                after.append(s.charAt(i));
                i++;
            }
        }
    }

    public static void main(String[] args) {

        // Example input string containing many words and one float
        String s = "c/c++ c#893725.1046java python";

        StringBuilder before = new StringBuilder();
        StringBuilder after  = new StringBuilder();

        extractFloatDigits(s, before, after);

        System.out.println("Before decimal: " + before);
        System.out.println("After decimal:  " + after);
    }
}



/*
run:

Before decimal: 893725
After decimal:  1046

*/

 



answered Sep 17 by avibootz
...