String Manipulation in Go: Finding Substring Occurrences

Introduction

Hello, and welcome to our last lesson in this course. Today, we will be tackling a common problem in the field of string manipulations with Go. We will learn how to find all occurrences of a substring within a larger string. The techniques you will master today can be utilized in numerous situations, such as text processing and data analysis. Are you ready to get started? Let's dive in!

Task Statement and Description

Here is the task for today: we have two slices of strings, both of identical lengths — the first contains the "original" strings and the second contains the substrings. Our goal is to detect all occurrences of each substring within its corresponding original string and, finally, return a slice that contains the starting indices of these occurrences. Remember, the index counting should start from 0.

Example: let's consider the following slices:

  • Original Slice: {"HelloWorld", "LearningGo", "GoForBroke", "BackToBasics"}
  • Substring Slice: {"loW", "ear", "o", "Ba"}.

The following are the expected outputs:

  • In "HelloWorld", "loW" starts at index 3.
  • In "LearningGo", "ear" starts at index 1.
  • In "GoForBroke", "o" appears at indices 1, 3, and 7.
  • In "BackToBasics", "Ba" starts at indices 0 and 6.

Thus, when findSubString([]string{"HelloWorld", "LearningGo", "GoForBroke", "BackToBasics"}, []string{"loW", "ear", "o", "Ba"}) is invoked, the function should return:

{
    "The substring 'loW' was found in the original string 'HelloWorld' at position(s) 3.",
    "The substring 'ear' was found in the original string 'LearningGo' at position(s) 1.",
    "The substring 'o' was found in the original string 'GoForBroke' at position(s) 1, 3, 7.",
    "The substring 'Ba' was found in the original string 'BackToBasics' at position(s) 0, 6."
}

Let's break it down step by step.

Step 1 - Creating the Output Slice

Initially, we need to create a space to store our results. For this task, a slice of strings would be ideal.

func solution(origStrs, substrs []string) []string {
    var result []string

Step 2 - Pairing Strings and Locating First Occurrence

To pair original strings with their substrings, we use a simple for loop. We can rely on a single loop index, as both slices share the same length. To find the first occurrence of each substring in the corresponding original string, we utilize the strings.Index function:

    for i := range origStrs {
        startPos := strings.Index(origStrs[i], substrs[i])

The strings.Index function returns the index of the first occurrence of the substring or -1 if it is not present.

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