Mastering Nested Loops and String Manipulation in Scala

Introduction

Hello and welcome to today's Scala lesson! We are going to dive into an engaging challenge that will test our abilities in string manipulation, leveraging the power of nested loops. Prepare yourself for an interesting journey 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. Sounds exciting, doesn't it? Let's get started!

Task Statement

Here's a detailed look at our task: We will work with a string that represents a sentence in which words are separated by spaces. Your task is to create a Scala function that identifies the odd-indexed characters of words that have an even number of characters. Then, you will combine these characters into a single string, maintaining the order in which they appear in the sentence.

Let's consider an example to foster a deep understanding: "Scala is a functional programming language." Here, the word Scala has 5 characters (an odd number), so it will be skipped. However, the word language has 8 characters (an even number), and we will select the odd-indexed characters from this word: specifically, 'a', 'g', and 'e'. Similarly, we select 's' from is, and 'u', 'c', 'i', 'n', and 'l' from functional. The word a will be skipped as it has an odd number of characters.

Thus, if our function is working correctly, it should return "aglscinl". This task highlights the versatility of loops and conditionals in solving various string challenges with Scala!

Solution Building: Step 1

We initiate our solution-building process by splitting the sentence into words. Scala provides us with the split method, which makes this task easy. The function separates the sentence into words at each space, giving us an array containing all the words in the sentence.

def solution(sentence: String): String = {
  val words = sentence.split(" ")
  // we will proceed progressively
}

Solution Building: Step 2

Now, let's delve into nested loops: an outer loop that iterates over every word and an inner operation that checks every character within each word. Firstly, we'll use an if condition that verifies whether a word has an even length. How do we do this? By using the modulus operator on the length of the word with 2. If this modulus is zero, our word has an even length!

def solution(sentence: String): String = {
  val words = sentence.split(" ")
  for (word <- words) {
    if (word.length % 2 == 0) {  // confirms whether the length of the word is even
      // we are building up our solution progressively
    }
  }
}
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