Calculating the sum of all numbers in a String in Java
In this tutorial, we will be calculating the sum of all numbers in a String in Java.
The problem is pretty simple. We are supposed to add up all the numbers in a string. The part where it gets complex is when there are two or multiple digit numbers. They are not supposed to be treated as individual digits but rather as a whole number.
Example:
Let the string be: Java23Dev56hlp4bufh
The numbers are not supposed to be treated as individual digits like 2, 3, 5, etc..
Rather the numbers in the string are: 23, 56 and 4
Hence the total is 23 + 56 + 4 = 83.
Program to calculate the sum of all numbers in a String in Java
import java.util.*; class sum { public static void main(String[]args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the string: "); String str = scan.next(); int j = 0, z = 10; int [] arr = new int [str.length()]; for(int i = 0; i < str.length(); i++) { if(str.charAt(i) >= 48 && str.charAt(i) <= 57) { arr[j] = str.charAt(i) - 48; while(i + 1 < str.length() && str.charAt(i + 1) >= 48 && str.charAt( i + 1) <= 57) { arr[j] = z * arr[j] + str.charAt(i + 1) - 48; i = i + 1; } j = j + 1; z = 10; } } int total = 0; for(int i = 0; i < arr.length; i++) { total = total + arr[i]; } System.out.println("The sum is: "+total); } }
Explanation
- Firstly we scan the input string and check for the occurrence of a number using a for loop.
- Next, when we encounter a number we check for consecutive numbers using a while loop.
- We store this number in an array.
- In the end, we iterate over the array to get the total Sum.
Output:
Enter the string: Code12speedy9.com The sum is: 21
Enter the string: fdsf34mgk123jfs3 The sum is: 160
Hope you’ve understood the code 🙂
Any questions feel free to drop in your comments.
You can also check:
what if i have spaces in between in the string and the continuous numbers with space will be taken as one number if i remove spaces in the string
please let me know how to do it