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.