Sunday, October 7, 2012

If an array is having integers/Char/special Char... Ex: "PST456DA85M2A!!23++46", find out the sum of integers.


/**
* Find the sum of numbers from given String.
* @param data Given String data.
* @return Sum of numbers from string.
*/
public int findSumOfNumbers(String data)
{
int sum = 0;
int count = 0;
if (data == null)
return sum;
for(int i =0 ; i< data.length(); i++)
{
int val = Character.getNumericValue(data.charAt(i));
if (val >= 0 && val < 10)
{
count = count * 10 + val;
}
else
{
System.out.println("Number : " +count);
sum += count;
System.out.println("Sum : " +sum);
count = 0;
}
}
sum += count;
return sum;
}

No comments: