Introduction

Hello and welcome! Today, we have an interesting and practical task that will enhance your Scala programming skills. Our focus will be on parsing strings and processing numbers through type conversions. So, get ready as we dive right into this challenge!

Task Statement and Description

The task at hand involves creating a Scala function named parseAndMultiplyNumbers. This function will take a string as input. This string is unique as it contains numbers and words mixed together in a free-spirited manner.

The function's job is to parse this input string, find all the numbers, convert these numbers (which are currently strings) into integer data types, and then multiply all these numbers together. The output will be the product of all those numbers!

To provide an example, for the input string "I have 2 apples and 5 oranges," our function should return the product of 2 and 5, which is 10.

Step-by-Step Solution Building: Step 1

The first step is to parse the string and capture the numbers. But how can we achieve this? We will sequentially search through the string.

Let's start by creating an empty string num, which will temporarily hold digits, and a mutable list numbers to collect all numbers found:

Scala
val inputString = "I have2apples and5oranges"
var num = ""
val numbers = scala.collection.mutable.ListBuffer[Int]()
Step-by-Step Solution Building: Step 2

The next move is to iterate through the input string character by character. If we encounter a digit, we add it to our num string. If the character is not a digit and num is not empty, it indicates the end of a number.

We then convert num to an integer, add it to the numbers list, and reset num back to an empty string. If the character is not a digit and num is empty, we move on without action.

for (char <- inputString) {
    if (char.isDigit) {
        num += char
    } else if (num.nonEmpty) {
        numbers.append(num.toInt)
        num = ""
    }
}
if (num.nonEmpty) {
    numbers.append(num.toInt)
}
println(numbers)

After running this code, the output will be ListBuffer(2, 5).

Step-by-Step Solution Building: Step 3
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal