Golang : Transform comma separated string to slice example
Got a request from a junior software developer from India. Her question is how to convert a given comma-separated string to slice or array in Golang.
For example:
from A,B,C,D
to [A B C D]
It is pretty common to encounter comma separated string in software development world. Below are two code examples on how to transform a comma-separated string to slice and back to a comma-separated string. To achieve this, use the strings.Fields()
and strings.Join()
functions. However, care must be taken to ensure that the comma in the input string must be removed first. Otherwise, the result will not be a slice that you can perform operations on properly.
Here you go!
package main
import (
"fmt"
"strings"
)
func main() {
str := "A,B,C,D"
fmt.Println(str)
// first, clean/remove the comma
cleaned := strings.Replace(str, ",", " ", -1)
// convert 'clened' comma separated string to slice
strSlice := strings.Fields(cleaned)
fmt.Println(strSlice)
//NOTE : If we don't clean/remove the comma from the string
// the resultant strSlice will look like a slice but....
// you won't be able to perform operation on it
// such as strSlice[:1]
fmt.Println(strSlice[:1]) // test if this is a SLICE or not
}
Output:
A,B,C,D
[A B C D]
[A]
and back to comma-separated string
package main
import (
"fmt"
"strings"
)
func main() {
strSlice := []string{"A", "B", "C", "D"}
fmt.Println(strSlice)
// convert slice back to comma-separated string
str := strings.Join(strSlice, ",")
fmt.Println(str)
}
Output:
Notice the square brackets and the comma?
[A B C D]
A,B,C,D
Happy coding!
References:
https://www.socketloop.com/tutorials/golang-how-to-join-strings
https://www.socketloop.com/tutorials/golang-convert-string-to-array-slice
See also : Golang : How to join strings?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.3k Golang : Change date format to yyyy-mm-dd
+6.4k Elasticsearch : Shutdown a local node
+32.6k Golang : How to check if a date is within certain range?
+5.8k Golang : Missing Subversion command
+19.6k Golang : Count JSON objects and convert to slice/array
+6.3k Golang : Combine slices of complex numbers and operation example
+7k Golang : Check if one string(rune) is permutation of another string(rune)
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+8.3k Golang : Another camera capture GUI application with GTK and OpenCV
+29.6k Golang : How to get HTTP request header information?
+19k Mac OSX : Homebrew and Golang
+8.5k Golang : Find duplicate files with filepath.Walk