golang convert "type []string" to string
Asked Answered
H

6

92

I see some people create a for loop and run through the slice as to create a string, is there an easier way to convert a []string to a string?

Will sprintf do it?

Hoarding answered 20/1, 2017 at 5:0 Comment(2)
Please show the actual problem you have: why do you have to convert a []string into string? You will agree that I keep bumping into this is no valid description.Nunciata
e.g. when you have a formatted json as a []string (because some pkg method returned it like that) and want to Unmarshal(data []byte, v interface{}) it like so: json.Unmarshal([]byte(strings.Join(jsonLines, "")), &model)Bezel
S
118

You can use strings.Join(arr \[\]string, separator string) string.

Shipmaster answered 20/1, 2017 at 5:6 Comment(0)
E
65

This is a simple example, which you can paste into the main function:

stringArray := []string {"Hello","world","!"}
justString := strings.Join(stringArray," ")
fmt.Println(justString)

And link to working example on playground.

Or using very simple function simple function

Eddins answered 20/1, 2017 at 6:14 Comment(1)
SCNR: Can this also be pasted into different functions than main? I mean it's good to have another example here.Nunciata
L
6

Will Sprint do it?

Yes indeed!

Here is another way to convert to a string if all you care about is that it is a string and not specifically how it looks (see answers above with strings.Join for a little more flexibility).

The advantage of this method (or variations such as Sprintf), is it will work with (almost) every other data such as maps and structs and any custom type that implements the fmt.Stringer inteface.

  stringArray := []string {"Hello","world","!"}
  justString := fmt.Sprint(stringArray)

Here is a link to a working example.

Legion answered 6/1, 2020 at 12:46 Comment(0)
M
4

It can be done easily using Join function by importing strings package. You need to pass the slice of strings and the separator you need to separate the elements in the string. (examples: space or comma)

func Join(elems []string, sep string) string

Example Code :

package main

import (
    "fmt"
    "strings"
)

func main() {
    sliceStr := []string{"a","b","c","d"}
    str := strings.Join(sliceStr,", ")
    fmt.Println(str)
}

//output: a, b, c, d
Monandrous answered 10/2, 2021 at 4:41 Comment(0)
X
2

If you don't care about the separator, you can use path:

package main
import "path"

func main() {
   a := []string{"south", "north"}
   s := path.Join(a...)
   println(s == "south/north")
}

https://golang.org/pkg/path#Join

Xanthene answered 28/3, 2021 at 22:16 Comment(0)
R
0
package main

import (
"fmt"
"reflect"
"strings"
)

func main() {
str1 := []string{"Trump", "In", "India", "On", "Feb 25"}
fmt.Println(str1)
fmt.Println(reflect.TypeOf(str1))

str2 := strings.Join(str1, " ")
fmt.Println(str2)
fmt.Println(reflect.TypeOf(str2))

str3 := strings.Join(str1, ", ")
fmt.Println(str3)
fmt.Println(reflect.TypeOf(str3))
}

Below is the ouput of the above program :-

go run hello.go
[Trump In India On Feb 25]
[]string
Trump In India On Feb 25
string
Trump, In, India, On, Feb 25
string

In the above code, first, we have defined a slice of string and then use the reflect package to determine the datatype of the slice. We have imported the “strings” module. With strings.Join() method, and we combine all elements of a string slice into a string. So, Golang string.Join() function that converts slice to string. We have passed the space(” “) as a delimiter. So we will join the slice elements by space.

The second argument to strings.Join() is the delimiter. For no delimiter, please use an empty string literal.

In the next step, we have again used the TypeOf() function to check the data type.

Then we have used the Golang string.Join() function again, but this time, we have passed (,) Comma. So, command separated values will be returned, which is also a type of string.

So, if you want to get CSV values in Golang, then you can use the Go string.Join() method.

You can also try with functions:-

// abc.go
package main

type deck []string

func (cards deck) toString() string {
    // converts slice to string
    return strings.Join([]string(cards), ",")

}


//main.go
package main

import "fmt"

func main() {
    cards := []string {"Trump", "In", "India", "On", "Feb 25"}
    fmt.Println(cards.toString())

}
Rosaniline answered 27/2, 2022 at 5:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.