Return the Shortest Words in Golang

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 }
Code language: Go (go)

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 }
Code language: Go (go)

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 }
Code language: Go (go)

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)) }) })
Code language: Go (go)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments