dtb81443 2018-09-02 22:43
浏览 1096

在Golang中获取字符串并将其拆分为字符串数组

I am trying to take an array and split it into an array of strings, this is my code:

if split != "" {

    for i := 0; i < len(split); i++ {

        for j := 0; j < len(split); j += 0 {

            splits := []byte(split)

            if splits[i] == ' ' {


                result := split[i] - split[j]

                for k := 0; k <= i; k++ {

                    fitting := make([]byte, result)
                    fitting[k] = splits[k]
                    fmt.Println(fitting[k])

                    if k > i-1 {

                        fittings := string(fitting[:])
                        word := []string{}
                        words := append(word, fittings)
                        fmt.Println(split, words)
                    }
                }

            }
        }
    }
}
return Strings(split)

and this is my test case:

fmt.Println(actual, expected)

for i := 0; i < len(expected); i++ {

    if actual[i] != expected[i] {
        t.Errorf("does not match")
        t.Fail()
    }

}
}

None of it is really working.

  • 写回答

1条回答 默认 最新

  • douci7521 2018-09-02 23:58
    关注

    I just need to know how I could possibly take a string such as "hi li le" and make it into an array of strings such as ["hi","li","le"]

    Yes with strings.Split or strings.Fields.

    for _, word := range strings.Fields("hi li le") {
        fmt.Println(word)
    }
    

    Here's a way to do it manually, for illustration.

    func split(tosplit string, sep rune) []string {
        var fields []string
    
        last := 0
        for i,c := range tosplit {
            if c == sep {
                // Found the separator, append a slice
                fields = append(fields, string(tosplit[last:i]))
                last = i + 1
            } 
        }
    
        // Don't forget the last field
        fields = append(fields, string(tosplit[last:]))
    
        return fields
    }
    
    func main() {
        str := "hello world stuff"
        for _,field := range split(str, ' ') {
            fmt.Println(field)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据