String Manipulation: Reversing Words in Go

Introduction

Hello, and welcome! Are you ready to elevate your string manipulation skills in Go? Today, we'll delve into a task that will bolster your comprehension of strings and enhance your creativity. The task involves splitting a string into words and then reversing each word as if reflected in a mirror. Does that sound interesting? Let's get started!

Task Statement and Description

You're tasked with considering a string filled with words and writing a Go function that accepts this string. The function should reverse the character order of each word and form a new string consisting of these reversed words.

Here's what you need to keep in mind:

  • The input string will contain between 1 and 100 words.
  • Each word in the string is a sequence of characters separated by whitespace.
  • The characters can range from a to z, A to Z, 0 to 9, or an underscore _.
  • The provided string may start or end with a space, and double spaces may also be present.
  • After reversing the words, your program should output a single string with the reversed words preserving their original order.

Example: consider the input string "Hello neat go_lovers_123". The function works as follows:

  • Hello becomes olleH
  • neat becomes taen
  • go_lovers_123 becomes 321_srevol_og

Afterward, it forms a single string with these reversed words, producing "olleH taen 321_srevol_og". Therefore, if you call reverseWords("Hello neat go_lovers_123"), the function should return "olleH taen 321_srevol_og".

Let's begin breaking this down!

Step 1 - Splitting the sentence

Our first task is to separate the words in the sentence. In Go, we can use the strings.Fields(s) function, which splits the string around each instance of one or more consecutive whitespace characters. Here's how you can do it:

import "strings"

inputStr := "Hello neat go_lovers_123"
words := strings.Fields(inputStr)

// Now, the slice 'words' holds all the words of the string

Alternatively, we could use strings.Split(s, " "), which splits based on a single space character. However, strings.Fields(s) is a better choice for this task because it handles multiple consecutive spaces and trims any surrounding spaces, ensuring that you get an accurate split of words without extra empty strings.

Step 2 - Reversing words

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