How to find the length of the second smallest word in a string with Go

1 Answer

0 votes
package main

import (
	"fmt"
	"sort"
	"strings"
)

func secondSmallestWordLength(s string) int {
	arr := strings.Split(s, " ")

	if len(arr) < 2 {
		return -1
	}

	lengths := make([]int, len(arr))
	for i, word := range arr {
		lengths[i] = len(word)
	}
	sort.Ints(lengths)

	return lengths[1]
}

func main() {
	str := "go java c++ python javascript"

	fmt.Println(secondSmallestWordLength(str))
}


/*
run:

3

*/

 



answered Oct 4, 2024 by avibootz

Related questions

...