Thursday, 7 August 2014

Java - Can you find the sum of numbers in a String

Consider a String "abc67uty89ty". Now can you write a program to calculate the value of 6+7+8+9

There might be other better solutions but here is what I did using Regular expression, which makes this quite easy.

In Java you can use regular expression to search and get index of a pattern. The two primary classes used are Pattern and Matcher.

The expression "\d" I use below is to get numeric values.

int getSumOfNumbersInAString(String input){
int sum=0;
String numericrExpr="\\d";
Pattern pattern=Pattern.compile(numericrExpr);
Matcher matcher = pattern.matcher(input);
int index=matcher.start();
int c=Integer.parseInt(input.substring(index, (index+1)));
return sum;

This will get you the sum.

No comments:

Post a Comment