I have an array of strings from which I need to extract the first words, convert them to integers and get the their sum.
Example:
["5 Apple", "5 Orange", "15 Grapes"]
Expected output => 25
My attempt:
["5","5","15"].map(&:to_i).sum
Let’s see different ways to find the sum of first n elements. Initialize sum = 0. Iterate over the array up to nth element and add the current element to sum. Return sum. Create scanner class object. Ask use length of the array. Initialize the array with given size. Ask the user for array elements. Iterate over the array. Initialize sum = 0.
Ask use length of the array. Initialize the array with given size. Ask the user for array elements. Iterate over the array. Initialize sum = 0. Iterate over the array up to nth element and add the current element to sum.
Sum of string array elements in java [duplicate] But the code int num = Integer.parseInt(element) gives NumberFormatException because Joe, Chandler, Rajat are not integers. So, how to resolve this problem. The answer should be the sum of 12+15+67=94.
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters.
I found the answer from your question.
["5 Apple", "5 Orange", "15 Grapes"].map(&:to_i).sum
In array if any integer convertable value is present then it will automatically convert into integer.
Map with #split
:
["5 Apple", "5 Orange", "15 Grapes"].map{|s| s.split.first.to_i }.sum
=> 25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With