开发者

How to extract number and String in java

开发者 https://www.devze.com 2023-01-19 09:17 出处:网络
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\";

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

Th开发者_StackOverflow中文版anks


Break up your problem:

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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消