HomeSearch

Golang Convert Slice to String: int, string Slices

Convert slices to strings. Transform a string slice into a string and an int slice into a string.

Convert slice, string. A slice contains string data. It contains int data. With strings.Join we can convert a string slice to a string.Slice

For slices with ints, or other types of elements, we can first convert a slice into a string slice. A method like strconv.Itoa can help.

String slice. Here we convert a string slice into a string. Our string slice has three elements. More can be added with append().

Strings.Join: We import the "strings" module. With strings.Join, we combine all elements of a string slice into a string.

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

Golang program that converts string slice to string package main import ( "fmt" "strings" ) func main() { values := []string{"one", "two", "three"} // Convert string slice to string. // ... Has comma in between strings. result1 := strings.Join(values, ",") fmt.Println(result1) // ... Use no separator. result2 := strings.Join(values, "") fmt.Println(result2) } Output one,two,three onetwothree

Int slice to string. Here we convert an int slice into a string. First we create a string slice from the data in the int slice. We use a for-range loop for this.For

Strconv.Itoa: This converts an int into a string. We then place these strings (text) into the valuesText slice.

Finally: We convert our string slice into a string with the strings.Join method.

Golang program that converts int slice to string package main import ( "fmt" "strconv" "strings" ) func main() { // The int slice we are converting to a string. values := []int{10, 200, 3000} valuesText := []string{} // Create a string slice using strconv.Itoa. // ... Append strings to it. for i := range values { number := values[i] text := strconv.Itoa(number) valuesText = append(valuesText, text) } // Join our string slice. result := strings.Join(valuesText, "+") fmt.Println(result) } Output 10+200+3000

Append runes. In Go we have another option for building up a string. We can append runes to a rune slice based on our data. Then we can convert the rune slice into a string.Strings: Runes

A summary. With strings.Join we convert a string slice into a string. Sometimes we can convert another type of data, like an int slice, into a string slice before using Join.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.