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

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -