Lesson 1
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:

Go
1import "strings" 2 3inputStr := "Hello neat go_lovers_123" 4words := strings.Fields(inputStr) 5 6// 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

Next, we need to reverse each word separated in the previous step. We'll reverse the characters of each word in Go by creating a helper function. Here's an example of how to reverse a string in Go:

Go
1func reverse(s string) string { 2 runes := []rune(s) 3 for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { 4 runes[i], runes[j] = runes[j], runes[i] 5 } 6 return string(runes) 7} 8 9reversedWords := []string{} 10 11for _, word := range words { 12 reversedWords = append(reversedWords, reverse(word)) 13} 14 15// 'reversedWords' now contains the reversed words

This code snippet:

  • Defines a reverse function to reverse strings.
  • Converts the input string s to a slice of runes to handle Unicode characters.
  • Uses a loop to swap characters from both ends toward the center: runes[i], runes[j] = runes[j], runes[i].
  • The loop utilizes simultaneous initialization and iteration of two variables.
  • Returns the reversed string by converting the runes back to a string.
  • Iterates over each word from the initial split, applies the reverse function, and stores reversed words in a slice reversedWords.
Step 3 - Joining the reversed words

Finally, we need to consolidate these reversed words into a single string, separated by spaces. We can achieve this using strings.Join() in Go. Here's how we do that:

Go
1result := strings.Join(reversedWords, " ")
Complete Solution

It remains for us to combine the code from the steps together in a function reverseWords and call it from main to test.

Go
1package main 2 3import ( 4 "fmt" 5 "strings" 6) 7 8func reverse(s string) string { 9 runes := []rune(s) 10 for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { 11 runes[i], runes[j] = runes[j], runes[i] 12 } 13 return string(runes) 14} 15 16func reverseWords(inputStr string) string { 17 words := strings.Fields(inputStr) 18 19 reversedWords := []string{} 20 for _, word := range words { 21 reversedWords = append(reversedWords, reverse(word)) 22 } 23 24 return strings.Join(reversedWords, " ") 25} 26 27func main() { 28 // Call the function 29 fmt.Println(reverseWords("Hello neat go_lovers_123")) // prints: 'olleH taen 321_srevol_og' 30}
Lesson Summary

Well done! By completing this lesson, you've sharpened your proficiency in manipulating strings in Go. You've specifically improved in reversing the order of characters in a word. I hope you're feeling confident and excited about your Go skills. Remember, mastering these skills requires frequent practice. Therefore, take some time to explore related problems and practice what you’ve learned. Enjoy the journey of learning!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.