dongluo6343 2017-06-15 17:16
浏览 40
已采纳

如何检查附加切片是否等于字符串?

So the plan is to have a string such as "a" in the slice, and once that turns into "a100" for example then stop running a for loop which is adding numbers to the end of it. When I try the code below it says "(mismatched types []string and string)", is this because I have to convert the slice into a string? If so, how do I do that? Thanks.

package main

import "fmt"

func main() {
    var s []string
    s = append(s, "a")
    fmt.Println(s)
    for i := 0; i <= 1000; i++ {
        s = append(s, i)
        if s == "a10" {
            fmt.Println("Worked", s)
        } else {
            fmt.Println(s)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dtl85148 2017-06-15 17:19
    关注

    You can convert an []string to a string` by doing:

    import "strings"
    
    //...
    
    if strings.Join(s, "") == "a10" {
          fmt.Println("Worked", s)
    } else {
          fmt.Println(s)
    }
    

    You also need to convert i (an int) to a string, most likely you would use strconv.Itoa. In the end, you code would look something like this: https://play.golang.org/p/gD5b5XFimJ

    package main
    
    import (
        "fmt"
        "strconv"
        "strings"
    )
    
    func main() {
        var s []string
        s = append(s, "a")
        fmt.Println(s)
        for i := 0; i <= 1000; i++ {
            s = append(s, strconv.Itoa(i))
            if strings.Join(s, "") == "a01" {
                fmt.Println("Worked", s)
                return
            } else {
                fmt.Println(s)
            }
        }
    }
    

    Although, you could also just not use an array and append to the string (or an []byte) directly...

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        var s := "a"
        fmt.Println(s)
        for i := 0; i <= 1000; i++ {
            s += strconv.Itoa(i)
            if s == "a01" {
                fmt.Println("Worked", s)
                return
            } else {
                fmt.Println(s)
            }
        }
    }
    

    To reset the array every time, just make the main method:

    for i := 0; i <= 1000; i++ {
        s := []string{"a"}
        s = append(s, strconv.Itoa(i))
        if strings.Join(s, "") == "a10" {
            fmt.Println("Worked", s)
            return
        } else {
            fmt.Println(s)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大