dongwei2610 2017-07-16 11:11
浏览 214
已采纳

将字符串作为字符数组访问以供在string.Join()方法中使用:GO语言

I am trying to access a string as a character array or as a rune and join with some separator. What is the right way to do it.

Here are the two ways i tried but i get an error as below

cannot use ([]rune)(t)[i] (type rune) as type []string in argument to strings.Join  

How does a string represented in GOLANG. Is it like a character array?

    package main

    import (
        "fmt"
        "strings"
    )

    func main() {
        var t = "hello"
        s := ""
        for i, rune := range t {
            s += strings.Join(rune, "
")
        }
        fmt.Println(s)
    }



    package main

    import (
        "fmt"
        "strings"
    )

    func main() {
        var t = "hello"
        s := ""
        for i := 0; i < len(t); i++ {
            s += strings.Join([]rune(t)[i], "
")
        }
        fmt.Println(s)
    }

I also tried the below way.BUt, it does not work for me.

var t = "hello"
    s := ""
    for i := 0; i < len(t); i++ {
        s += strings.Join(string(t[i]), "
")
    }
    fmt.Println(s)
  • 写回答

1条回答 默认 最新

  • doulu2576 2017-07-16 11:30
    关注

    The strings.Join method expects a slice of strings as first argument, but you are giving it a rune type.

    You can use the strings.Split method to obtain a slice of strings from a string. Here is an example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog