package code.asgard.strings;

import java.util.Scanner;

/**
 * @author Sagar
 */
public class SumOfNumbers {
    /**
     * This method calculated total sum of numbers in an input string.
     *
     * @param inputStr  Input string
     * @return          Sum of Number in string.
     *                  E.g. Sagar100V1Hadawale10 => 111
     */
    private static int calculateSumOfNumbers(String inputStr) {
        if (inputStr == null || inputStr.length() == 0) {
            System.out.println("Input string is null or empty.");
            return 0;
        }

        String copyOfInputStr = inputStr.replaceAll("\\s", "").toLowerCase();
        char[] chList = copyOfInputStr.toCharArray();

        String number = "";
        int sum = 0;
        int asciiValue;

        for(char ch : chList) {
            asciiValue = ch;

            // The digit ASCII values are in between 48 and 57
            if (asciiValue >= 48 && asciiValue <= 57) {
                number = number + ch;
            } else {
                if (number.length() != 0) {
                    sum = sum + Integer.valueOf(number);
                }
                number = "";
            }
        }

        // The end of the string might end in numbers so that we will not a chance to add sum.
        // Below is the last digit check.
        if(number.length() != 0) {
            sum = sum + Integer.valueOf(number);
        }

        return sum;
    }

    public static void main(String[] args) {
        System.out.println("Please enter an input string to calculate sum of numbers: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        System.out.println("Sum of numbers in string: " + calculateSumOfNumbers(input));
    }
}
