0

Have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number.

For example: if str is "88Hello 3World!" the output should be 91. You will have to differentiate between single-digit numbers and multiple-digit numbers like in the example above. So "55Hello" and "5Hello 5" should return two different answers. Each string will contain at least one letter or symbol. import java.util.Scanner;

final String NUMBERS = "0123456789";

int sum = 0;

char[] chars = str.toCharArray();
StringBuilder number = new StringBuilder("");
for (int i = 0; i < chars.length; i++) {
if (NUMBERS.indexOf(chars[i]) != -1) {
number.append(chars[i]);

if (i == chars.length - 1) {
sum += Integer.valueOf(number.toString());
}
} else if (number.length() != 0) {
sum += Integer.valueOf(number.toString());
number.setLength(0);
}
}

return sum;
}

public static void main (String[] args) {
Scanner s = new Scanner(System.in);
}
}

Using the JavaScript language, have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number.

For example: if str is "88Hello 3World!" the output should be 91. You will have to differentiate between single digit numbers and multiple digit numbers like in the example above. So "55Hello" and "5Hello 5" should return two different answers. Each string will contain at least one letter or symbol.

var tot = 0;
str = str.replace(/[^0-9\.]+/g," ").split(" ");
for (var i = 0; i < str.length; i++) {
tot += Number(str[i]);
}
}

Explanation

I only want numbers in the string so I am using RegExp to remove everything that is not a number. Then convert that to an array. Loop thru each number in the array and add tot to get the answer.

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.