Return the Shortest Words in Golang

1 min read 207 words

The challenge

Given a string of words, return the length of the shortest word(s).

The input string will never be empty and you do not need to account for different data types.

The solution in Golang

Option 1:

package solution
import "strings"

func FindShort(s string) int {
  shortest := len(s)
  for _, word := range strings.Split(s, " ") {
    if len(word) < shortest {
      shortest = len(word)
    }
  }
  return shortest
}

Option 2:

package solution
import "strings"

func FindShort(s string) (c int) {
  words := strings.Split(s," ");
  for _,word := range words {
    if c == 0 || len(word) < c {
       c = len(word);
    }
  }
  return
}

Option 3:

package solution
import "strings"

func FindShort(s string) (c int) {
  for _, word := range strings.Fields(s) {
    if c == 0 || len(word) < c {
      c = len(word)
    }
  }
  return c
}

Test cases to validate our solution

package our_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Test Example", func() {
  It("should test that the solution returns the correct value", func() {
    Expect(FindShort("bitcoin take over the world maybe who knows perhaps")).To(Equal(3))
    Expect(FindShort("turns out random test cases are easier than writing out basic ones")).To(Equal(3))
    Expect(FindShort("Let's travel abroad shall we")).To(Equal(2))
  })
})
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts