英文:
Access a string as a character array for using in strings.Join() method: GO language
问题
我正在尝试将字符串作为字符数组或rune数组访问,并与某个分隔符连接起来。正确的方法是什么?
以下是我尝试的两种方式,但是我得到了以下错误:
cannot use ([]rune)(t)[i] (type rune) as type []string in argument to strings.Join
在Golang中,字符串是如何表示的?它是否像字符数组一样?
package main
import (
"fmt"
"strings"
)
func main() {
var t = "hello"
s := ""
for i, rune := range t {
s += strings.Join([]string{string(rune)}, "\n")
}
fmt.Println(s)
}
package main
import (
"fmt"
"strings"
)
func main() {
var t = "hello"
s := ""
for i := 0; i < len(t); i++ {
s += strings.Join([]string{string(t[i])}, "\n")
}
fmt.Println(s)
}
我还尝试了以下方式,但对我来说不起作用。
var t = "hello"
s := ""
for i := 0; i < len(t); i++ {
s += strings.Join([]string{string(t[i])}, "\n")
}
fmt.Println(s)
英文:
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, "\n")
}
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], "\n")
}
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]), "\n")
}
fmt.Println(s)
答案1
得分: 1
strings.Join 方法期望作为第一个参数传入一个字符串切片,但你给它传入了一个 rune 类型。
你可以使用 strings.Split 方法从字符串中获取一个字符串切片。这里有一个示例。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论