Tuesday, April 2, 2013

Java: Get Sum of Numbers in a String

Download Link: http://txtup.net/dQNDr

/*

Source Question: betterprogrammer.com
Please implement this method to
return the sum of all integers found in the parameter String. You can assume that
integers are separated from other parts with one or more spaces (' ' symbol).
For example, s="12 some text 3 7", result: 22 (12+3+7=22)
*/

 

  1. import java.util.regex.Matcher;

  2. import java.util.regex.Pattern;

  3. public class GetSumOfNumbers {

  4. public static void main(String[] args) {


  5. System.out.println(getSumOfNumbers("ss34 gbb 65"));

  6. }


  7. public static int getSumOfNumbers(String s) {

  8. /*

  9. Please implement this method to

  10. return the sum of all integers found in the parameter String. You can assume that

  11. integers are separated from other parts with one or more spaces (' ' symbol).

  12. For example, s="12 some text 3 7", result: 22 (12+3+7=22)

  13. */

  14. //s="kkk 4 jj 9d kj 99 kjdj 9 kj 9";

  15. Pattern p = Pattern.compile("\\d+");

  16. Matcher m = p.matcher(s);

  17. int sum=0;

  18. while(m.find())

  19. {

  20. //System.out.println(m.start()+" "+m.end());

  21. sum = sum + Integer.parseInt(s.substring(m.start(), m.end()));

  22. }


  23. return sum;

  24. }

  25. }


Download Link: http://txtup.net/dQNDr

0 comments: