/*
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)
*/
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class GetSumOfNumbers {
- public static void main(String[] args) {
- System.out.println(getSumOfNumbers("ss34 gbb 65"));
- }
- public static int getSumOfNumbers(String s) {
- /*
- 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)
- */
- //s="kkk 4 jj 9d kj 99 kjdj 9 kj 9";
- Pattern p = Pattern.compile("\\d+");
- Matcher m = p.matcher(s);
- int sum=0;
- while(m.find())
- {
- //System.out.println(m.start()+" "+m.end());
- sum = sum + Integer.parseInt(s.substring(m.start(), m.end()));
- }
- return sum;
- }
- }
Download Link: http://txtup.net/dQNDr

0 comments:
Post a Comment