How to find the second largest word in a string with Go

1 Answer

0 votes
package main

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

func secondLargestWordInString(s string) string {
	words := strings.Fields(s)

	if len(words) < 2 {
		return ""
	}

	sort.Slice(words, func(i, j int) bool {
		return len(words[i]) > len(words[j])
	})

	return words[1]
}

func main() {
	str := "c cpp scala go python java"

	fmt.Println("Second largest word:", secondLargestWordInString(str))
}



/*
run:

Second largest word: scala

*/

 



answered Oct 3, 2024 by avibootz

Related questions

...