String Manipulation with Nested Loops in Go

Introduction

Hello and welcome to today's lesson! We are going to unravel an engaging challenge that will sharpen our skills in string manipulation using Go. This lesson will place particular emphasis on nested loops. Get ready for an intriguing task as we explore how to extract odd-indexed characters from each word in a sentence, but only if the word has an even number of characters. Does that sound exciting? Let's dive in!

Task Statement

The task we'll be demonstrating is as follows: we will work with a string representing a sentence in which words are separated by spaces. Your challenge involves creating a Go function that identifies the odd-indexed characters of words that have an even number of characters and then combines these characters into a single string, maintaining the order in which they appeared in the sentence.

Consider this example: "Go is a powerful language for programming" The word Go has 2 characters (an even number), and we'll select the odd-indexed character from this word, specifically, o. The word is also has 2 characters, and we'll select the odd-indexed character s. Similarly, we'll select o, e, f, l from powerful, a, g, a, and e from language. We'll skip the words a, for, and programming because they have odd lengths.

If our function is working correctly, it should return osoeflagae. Isn't it fascinating to see what we can extract from a simple sentence?

Step 1 - Splitting Sentence into Words

We will commence our solution-building process by splitting the sentence into words. In Go, this can be efficiently achieved using the strings.Fields function, which splits the string into a slice of words using whitespace characters as delimiters.

package main

import (
    "fmt"
    "strings"
)

func solution(sentence string) string {
    words := strings.Fields(sentence)
    // we will proceed from here
    return ""
}

Step 2 - Outer Loop & Length Check

We now introduce nested loops: an outer loop that iterates over every single word, and an inner loop that checks every character within each word. First, we'll use an if condition to verify whether a word has an even length. We can determine this by checking whether len(word) % 2 == 0. If it does, the word has an even length!

package main

import (
    "fmt"
    "strings"
)

func solution(sentence string) string {
    words := strings.Fields(sentence)
    var result string

    for _, word := range words {
        if len(word)%2 == 0 {  // check if the length of the word is even
            // we are building up our solution gradually
        }
    }
    return result
}
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