How to write sequence of words from command line

Hi there, I was trying to do this exercise:
Write a program that receives from the command line a series of arbitrary length of words
and print the longest word. In case there are more words of maximum length, the program prints
the last. For example, if the user inserts the sequence of words one two four thirteen the program
press thirteen.
Note that:

  1. the data comes from the command line
  2. we have a sequence of data that can be processed in series, in a uniform manner
  3. these are strings
  4. All data entered at startup of the program are already stored in slice os.Args

I was writing code but idk how to set func main related to the arguments written in command line, I’ve written this code:
package main

import (

"fmt"

"os"

"strings"

)

func longestword(s string) (best string) {

for _, word:= range strings.Split(s, " ") {

    if len(word) > len(best) {

        best = word

    }

}

return

}

func main() {

var arg string

for _, arg = range os.Args[1:] {

    fmt.Println(arg)

}

}


Is there some funcion that identify the longest word?

How about sorting the strings and then taking the first element?

package main

import (
	"fmt"
	"os"
	"sort"
)

func main() {
	if len(os.Args) > 1 {
		s_data := os.Args[1:]
		sort.Slice(s_data, func(i, j int) bool { return len(s_data[i]) >= len(s_data[j]) })
		fmt.Printf("The longest command line arg: '%s'\n", s_data[0])
	}
}

Not that anyone would notice in this use case, but sorting is O(n log n) and the problem can be solved with the O(n) linear search in OP’s code. OP just needs fix a couple small errors and put the parts together correctly.

If I understand what you are asking you are looking for os.Args:

Hope this helps.

-Mike