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

huangapple go评论159阅读模式
英文:

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 (
    	&quot;fmt&quot;
    	&quot;strings&quot;
    )
    
    func main() {
    	var t = &quot;hello&quot;
    	s := &quot;&quot;
    	for i, rune := range t {
    		s += strings.Join(rune, &quot;\n&quot;)
    	}
    	fmt.Println(s)
    }
    
    
    
    package main
    
    import (
    	&quot;fmt&quot;
    	&quot;strings&quot;
    )
    
    func main() {
    	var t = &quot;hello&quot;
    	s := &quot;&quot;
    	for i := 0; i &lt; len(t); i++ {
    		s += strings.Join([]rune(t)[i], &quot;\n&quot;)
    	}
    	fmt.Println(s)
    }

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

var t = &quot;hello&quot;
	s := &quot;&quot;
	for i := 0; i &lt; len(t); i++ {
		s += strings.Join(string(t[i]), &quot;\n&quot;)
	}
	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.

huangapple
  • 本文由 发表于 2017年7月16日 19:11:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/45127882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定