2

i want to extract number and add these numbers using Java and String remain same.

String as-

String msg="1,2,hello,world,3,4";

output should come like- 10,hello,world

Thanks

Sameek Mishra
  • 9,174
  • 31
  • 92
  • 118

4 Answers4

5

Break up your problem:

  1. parsing into tokens
  2. converting tokens into objects
  3. operate on objects
duffymo
  • 305,152
  • 44
  • 369
  • 561
5
String pieces[] = msg.split(",");  
int sum=0;
StringBuffer sb = new StringBuffer();
for(int i=0;i < pieces.length;i++){

      if(org.apache.commons.lang.math.NumberUtils.isNumber(pieces[i])){
             sb.appendpieces[i]();
      }else{
             int i = Integer.parseInt(pieces[i]));
             sum+=i;    
      }

 }
 System.out.println(sum+","+sb.);
 }
jmj
  • 237,923
  • 42
  • 401
  • 438
1
String[] parts = msg.split(",");
int sum = 0;
StringBuilder stringParts = new StringBuilder();
for (String part : parts) {
    try {
        sum += Integer.parseInt(part);
    } catch (NumberFormatException ex) {
        stringParts.append("," + part);
    }
}
stringParts.insert(0, String.valueOf(sum));

System.out.println(stringParts.toString()); // the final result

Note that the above practice of using exceptions as control flow should be avoided almost always. This concrete case is I believe an exception, because there is no method that verifies the "parsability" of the string. If there was Integer.isNumber(string), then that would be the way to go. Actually, you can create such an utility method. Check this question.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 3
    Isn't relying on exceptions to control program flow a bad practice? Otherwise it looks like a pretty nice simplistic solution with close to no accidental complexity. – vstoyanov Oct 06 '10 at 11:18
  • @vstoyanov there was a discussion about that specific case (with parsing numbers/date), let me find it. Generally, yes, it's a bad practice to rely on exceptions, but since there is no method to verify the parsability.. – Bozho Oct 06 '10 at 11:20
  • @vstoyanov http://stackoverflow.com/questions/3684079/is-it-ok-to-try-catch-something-just-to-check-if-an-exception-was-thrown-or-not/3684093#3684093 – Bozho Oct 06 '10 at 11:22
  • for (String part : parts) please detail this statement what it does. – Sameek Mishra Oct 06 '10 at 11:31
  • this is the foreach loop introduced in Java 5. It loops all elements of the array/collection – Bozho Oct 06 '10 at 11:32
  • @Bozho http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/NumberUtils.html there is a api to check , check my answer – jmj Oct 06 '10 at 11:57
0

Here's a very simple regex version:

/**
 * Use a constant pattern to skip expensive recompilation.
 */
private static final Pattern INT_PATTERN = Pattern.compile("\\d+",
    Pattern.DOTALL);

public static int addAllIntegerOccurrences(final String input){
    int result = 0;
    if(input != null){
        final Matcher matcher = INT_PATTERN.matcher(input);
        while(matcher.find()){
            result += Integer.parseInt(matcher.group());
        }
    }
    return result;

}

Test code:

public static void main(final String[] args){
    System.out.println(addAllIntegerOccurrences("1,2,hello,world,3,4"));
}

Output:

10

Caveats:

This will not work if the numbers add up to anything larger than Integer.Max_VALUE, obviously.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588