0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.