Java Online Compiler
Example: SumNumbersInStringByIteration in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// SumNumbersInStringByIteration public class Main { public static void main(String[] args) { String inputString = "I have 10 apples, 5 bananas, and 2 dozens of grapes, costing $15 total."; int sum = 0; StringBuilder currentNumber = new StringBuilder(); // Step 1: Iterate through each character of the string for (int i = 0; i < inputString.length(); i++) { char ch = inputString.charAt(i); // Step 2: Check if the character is a digit if (Character.isDigit(ch)) { currentNumber.append(ch); // Append digit to current number string } else { // Step 3: If not a digit, and we have a number built, parse and add it to sum if (currentNumber.length() > 0) { sum += Integer.parseInt(currentNumber.toString()); currentNumber.setLength(0); // Reset StringBuilder for the next number } } } // Step 4: After the loop, check if there's a number at the very end of the string if (currentNumber.length() > 0) { sum += Integer.parseInt(currentNumber.toString()); } System.out.println("The original string is: \"" + inputString + "\""); System.out.println("Sum of numbers: " + sum); } }
Output
Clear
ADVERTISEMENTS