One-liner to transform []int into string
You can always json.Marshal
:
data := []int{1,2,3}
s, _ := json.Marshal(data)
fmt.Println(string(s))
// output: [1, 2, 3]
fmt.Println(strings.Trim(string(s), "[]"))
//output 1,2,3
I've just run into the same problem today, since I've not found anything on standard library, I've recompiled 3 ways to do this conversion
Create a string and appending the values from the array by converting it using strconv.Itoa:
func IntToString1() string {
a := []int{1, 2, 3, 4, 5}
b := ""
for _, v := range a {
if len(b) > 0 {
b += ","
}
b += strconv.Itoa(v)
}
return b
}
Create a []string, convert each array value and then return a joined string from []string:
func IntToString2() string {
a := []int{1, 2, 3, 4, 5}
b := make([]string, len(a))
for i, v := range a {
b[i] = strconv.Itoa(v)
}
return strings.Join(b, ",")
}
Convert the []int to a string and replace / trim the value:
func IntToString3() string {
a := []int{1, 2, 3, 4, 5}
return strings.Trim(strings.Replace(fmt.Sprint(a), " ", ",", -1), "[]")
}
Performance is quite different depending on implementation:
BenchmarkIntToString1-12 3000000 539 ns/op
BenchmarkIntToString2-12 5000000 359 ns/op
BenchmarkIntToString3-12 1000000 1162 ns/op
Personally, I'll go with IntToString2, so the final function could be an util package in my project like this:
func SplitToString(a []int, sep string) string {
if len(a) == 0 {
return ""
}
b := make([]string, len(a))
for i, v := range a {
b[i] = strconv.Itoa(v)
}
return strings.Join(b, sep)
}
To convertA := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
to a one line delimited string like
"1,2,3,4,5,6,7,8,9"
use:
strings.Trim(strings.Join(strings.Fields(fmt.Sprint(A)), delim), "[]")
or:
strings.Trim(strings.Join(strings.Split(fmt.Sprint(A), " "), delim), "[]")
or:
strings.Trim(strings.Replace(fmt.Sprint(A), " ", delim, -1), "[]")
and return it from a function such as in this example:
package main
import "fmt"
import "strings"
func arrayToString(a []int, delim string) string {
return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim, -1), "[]")
//return strings.Trim(strings.Join(strings.Split(fmt.Sprint(a), " "), delim), "[]")
//return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(a)), delim), "[]")
}
func main() {
A := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(arrayToString(A, ",")) //1,2,3,4,5,6,7,8,9
}
To include a space after the comma you could call arrayToString(A, ", ")
or conversely define the return as return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim + " ", -1), "[]")
to force its insertion after the delimiter.