String Manipulation and Nested Loops

Introduction

Welcome to this engaging lesson on string manipulation! In this lesson, we will dive into the fundamental concept of nested loops and explore them through an intriguing challenge. Our task will involve extracting particular characters from words within a sentence using these loops. Are you ready to embark on this fascinating exploration? Let's get started!

Task Statement

The task we'll undertake is as follows: We will work with a string that represents a sentence where words are separated by spaces. Your challenge is to create a function that identifies the odd-indexed characters of words with an even number of characters, including punctuation marks as part of the word's length, and combines these characters into a single string, preserving the order in which they appeared in the sentence.

Consider this example: "TypeScript programming language is versatile." The word TypeScript has 10 characters (an even number), and we'll select the odd-indexed characters from this word, namely y, e, c, i, t. Similarly, from language, we select a, g, a, e; from is, we select s; and from versatile., including the punctuation, we select e, s, t, l, .. We'll skip the word programming as it has an odd length.

The expected final output for our function should be "yecitagaestl.". Let's delve into how to achieve this!

Solution Building: Step 1

We'll begin by splitting the sentence into words, which will be stored in an array.

function oddCharsFromEvenWords(sentence: string): string {
    const words = sentence.split(" ");
    // we will proceed progressively
}

Solution Building: Step 2

Now, we introduce nested loops: an outer loop that iterates over each word and an inner loop that checks every character within the word. We'll use an if condition to verify if a word has an even length, determined by checking if the length of the word mod 2 equals zero.

function oddCharsFromEvenWords(sentence: string): string {
    const words: string[] = sentence.split(" ");

    for (const w of words) {
        if (w.length % 2 === 0) {  // checks if the length of the word is even
            // we are building up our solution gradually
        }
    }
}
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