14 Dec 2017

how to get the sum of all number given in between a sentence or a string.


the problem is that we have to find the sum of all number which is in between the sentence.for example if there is a sentence ..
String str="hello ,10, this, 56 ,is 80, java90";
then have to calculate the sum of 10,56,80,90 which is equal 236.

for this we will use the method useDelimiter() to get the sum of that number.here is the code snippet for that.

import java.util.*;
class SplitWithoutSplitMethodUsingDelimeter
{
          public static void main(String[] args)
          {
                   String str="hello ,10, this, 56 ,is 80, java90";
                   Scanner scn=new Scanner(str).useDelimiter("[^0-9]+");
                   //program to sum number given between string
                   //program to extract number from string
                   int sum=0;
                   while(scn.hasNext())
                             {
                             sum+=scn.nextInt();
                             }
                   System.out.println("sum::"+sum);
          }
}

the above program will extract the number from given string and add them. 

Output

sum::236