java - To print the sum of the numbers(not digits) in a string -


i asked write function in java sum numbers(not digits) in string. e.g. if string abc35zz400tt15, output should 450.

this wrote :

 public static void getsum(string a){         string[] arr=a.split("(?<=\\d)(?=\\d)|(?<=\\d)(?=\\d)");         int sum=0;         for(int i=0;i<arr.length;i++){             if(pattern.matches("[0-9]+", arr[i]))         sum+=integer.parseint(arr[i]);     }     system.out.println(sum);     } 

is there more efficient way didn't satisfied above code.

if forward efficiency regex matching , object allocations overkill task. can scan string backwards , accumulate number:

int currentpower = 1; int length = string.length(); int value = 0;  (int = string.length()-1; >= 0; --i) {   char curchar = string.charat(i);   if (curchar >= '0' && curchar <= '9') {     value += (curchar - '0') * currentpower;     currentpower *= 10;   }   else     currentpower = 1; } 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -