Sameek Mishra
Sameek Mishra

Reputation: 9384

How to extract number and String in java

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

Upvotes: 2

Views: 2700

Answers (4)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

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.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240900

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

Upvotes: 5

Bozho
Bozho

Reputation: 597106

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.

Upvotes: 1

duffymo
duffymo

Reputation: 308763

Break up your problem:

  1. parsing into tokens
  2. converting tokens into objects
  3. operate on objects

Upvotes: 5

Related Questions