Home
Map
Convert Slice to String: int, string SlicesConvert slices to strings. Transform a string slice into a string and an int slice into a string.
Go
This page was last reviewed on Mar 9, 2023.
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
Other types. 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().
Start 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.
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) }
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
Important Itoa() 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.
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) }
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.
Convert String
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 9, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.