猿问

无法分配给 v[i],引用数组问题?

我正在尝试解决一个难题来练习我的围棋。但是,我有点卡住了,这个错误不是很有帮助。


./prog.go:22:23: 不能分配给 v[j]


./prog.go:22:23: 不能分配给 v[wLen - 1 - j]


func SpinWords(str string) string {

    ws := strings.Split(str, " ")

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

        v := ws[i]

        wLen := len(v)


        if wLen > 4 {

            for j := 0; j < wLen/2; j++ {

                v[j], v[wLen-1-j] = v[wLen-1-j], v[j]

            }

            ws[i] = v

        }

    }


    return strings.Join(ws, " ")

}

这里几乎可以工作的代码:https: //play.golang.org/p/j9BYk642bFa


GCT1015
浏览 105回答 2
2回答

达令说

您不能分配给 of 的元素,v因为v它是一个字符串,而字符串是不可变的。您可以将字符串转换为[]byte第一个,然后使用它的元素,但如果您的字符串包含多字节字符,则不安全。v:=[]byte(ws[i])或者您可以将字符串转换为 a[]rune并使用它:v:=[]rune(ws[i])然后您可以分配给 的元素v,完成后,将其转换回字符串:str:=string(v)

慕容3067478

如果要执行该操作,则必须将单词从字符串转换为 []rune此代码有效:)package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; result := SpinWords("Welcome to the jungle we got fun and games")&nbsp; &nbsp; fmt.Println(result)}func SpinWords(str string) string {&nbsp; &nbsp; ws := strings.Split(str, " ")&nbsp; &nbsp; for i := 0; i < len(ws); i++ {&nbsp; &nbsp; &nbsp; &nbsp; v := ws[i]&nbsp; &nbsp; &nbsp; &nbsp; wLen := len(v)&nbsp; &nbsp; &nbsp; &nbsp; if wLen > 4 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; vinrune := []rune(v)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < wLen/2; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; vinrune[j], vinrune[wLen-1-j] = vinrune[wLen-1-j], vinrune[j]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v = string(vinrune)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ws[i] = v&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return strings.Join(ws, " ")}
随时随地看视频慕课网APP

相关分类

Go
我要回答