在GO中读取一些字符串并打印最长字符串的最佳方式

我快疯了。我正在尝试编写一个程序,该程序读取一些字符串(在我的情况下为5)并打印最长的字符串。我已经谷歌和搜索在这里,但我不喜欢任何东西...


package main


import "fmt"


func main() {

    var t1, t2, t3, t4, t5 string

    fmt.Scan(&t1, &t2, &t3, &t4, &t5)

    var l1, l2, l3, l4, l5 int

    var max int = -50000

    l1 = len(t1)

    l2 = len(t2)

    l3 = len(t3)

    l4 = len(t4)

    l5 = len(t5)

    var longest string = ""

    if l1 > max {

        l1 = max

    }

    if l2 > max {

        l2 = max

    }

    if l3 > max {

        l3 = max

    }

    if l4 > max {

        l4 = max

    }

    if l5 > max {

        l5 = max

    }


    fmt.Println(max)

}


慕田峪9158850
浏览 111回答 1
1回答

米琪卡哇伊

在这里,我编写了简单的代码来做到这一点。如上所述,跟随A Tour of Go,并进一步了解围棋循环。Flimzypackage mainimport "fmt"func main() {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; t := make([]string, 5)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//scan strings first&nbsp; &nbsp; for&nbsp; i := range t {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Scan(&t[i])&nbsp; &nbsp; }&nbsp; &nbsp; var longest string = ""&nbsp; &nbsp; &nbsp; &nbsp; // compare longest&nbsp; &nbsp; for _, s := range t {&nbsp; &nbsp; &nbsp; &nbsp; if len(longest) < len(s) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; longest = s&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(`longest := `,longest)}您可以减少第一个循环并按照以下方式进行。扫描字符串并在一个循环中进行比较。package mainimport "fmt"func main() {&nbsp; &nbsp; t := make([]string, 5)&nbsp; &nbsp; var longest string = ""&nbsp; &nbsp; for i, _ := range t {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Scan(&t[i])&nbsp; &nbsp; &nbsp; &nbsp; if len(longest) < len(t[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; longest = t[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(`longest := `,longest)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go