find the kth longest word in a string in go

To find the k-th longest word in a string, we first need to break down the string into individual words. We can do this by splitting the string using the strings.Split() function. Once we have a list of words, we can sort them in descending order based on their length. Finally, we can retrieve the k-th longest word from the sorted list.

Here is a sample code to achieve this in Go:

main.go
package main

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

func kthLongestWord(input string, k int) string {
    // Split the string into individual words
    words := strings.Fields(input)

    // Sort the words in descending order based on length
    sort.Slice(words, func(i, j int) bool {
        return len(words[i]) > len(words[j])
    })

    // Retrieve the k-th longest word from the sorted list
    if k > 0 && k <= len(words) {
        return words[k-1]
    }

    // Return an empty string if k is out of range
    return ""
}


func main() {
    input := "The quick brown fox jumps over the lazy dog"
    k := 2
    kthLongest := kthLongestWord(input, k)
    fmt.Printf("%dth longest word is %s", k, kthLongest)
}
729 chars
34 lines

In this code, we use the strings.Fields() function to split the input string into a slice of individual words. The sort.Slice() function is used to sort the words slice in descending order based on length. Finally, we retrieve the k-th longest word from the sorted slice and return it. The main function demonstrates how to enter input string and k and retrieve the result.

gistlibby LogSnag