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

2
  • all are saperated by commma ? Commented Oct 6, 2010 at 11:13
  • 1
    I believe a regular expression will do the trick here. Commented Oct 6, 2010 at 11:21

4 Answers 4

5

Break up your problem:

  1. parsing into tokens
  2. converting tokens into objects
  3. operate on objects
Sign up to request clarification or add additional context in comments.

Comments

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.);
 }

2 Comments

@Chankey yeah it was typo. Thanks
Sorry for the downvote... it seems in this special case, it IS legit... but thanks for the update. +1
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.

6 Comments

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 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..
for (String part : parts) please detail this statement what it does.
this is the foreach loop introduced in Java 5. It loops all elements of the array/collection
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.