Parsing and Multiplying Numbers in Go

Introduction

Welcome! Today, we have a fascinating and practical task that will test your Go programming skills. We'll be working on parsing strings and performing type conversions. Let's get started!

Task Statement and Description

Our task for the day involves creating a Go function named ParseAndMultiplyNumbers(). This function is designed to accept a string as input. The input is a playful mix of numbers and words. The goal of this function is to analyze the string, extract all the numbers, convert these numbers (currently string types) into integer data types, and then multiply these numbers together to produce a final result.

For example, given the input string "I have 2 apples and 5 oranges," our function should return the product of 2 and 5, which is 10.

Step 1 - Initialize Variables

The primary task is to parse the string and identify the numbers. To do this in Go, let's create an empty string, num, to accumulate digits and a slice numbers to collect all the numbers we find:

inputString := "I have 2 apples and 5 oranges"
num := ""
var numbers []int

Step 2 - Parse and Extract Numbers

The next step involves iterating through the input string character by character. When we encounter a digit, we append it to our num string. If a character isn't a digit and num isn't empty, it means we've reached the end of a number.

At this point, we convert num to an integer using strconv.Atoi, add it to the numbers slice, and reset num to an empty string. If the character isn't a digit and num is empty, we simply skip it and continue.

import (
    "fmt"
    "strconv"
    "unicode"
)

for _, ch := range inputString {
    if unicode.IsDigit(ch) {
        num += string(ch)
    } else if num != "" {
        number, err := strconv.Atoi(num)
        if err == nil {
            numbers = append(numbers, number)
        }
        num = ""
    }
}
if num != "" {
    number, err := strconv.Atoi(num)
    if err == nil {
        numbers = append(numbers, number)
    }
}

After running this code, the output should be a slice of integers [2, 5].

Step 3 - Multiply Extracted Numbers

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