One-Line Transformation of []int to String with Delimiter
In Go, it is possible to convert a slice of integers ([]int) to a string with a custom delimiter in a single line of code. Consider the need to transform []int{1, 2, 3} into "1, 2, 3" with a delimiter of choice.
A comprehensive solution that leverages multiple string manipulation functions is available:
strings.Trim(strings.Replace(fmt.Sprint(A), " ", delim, -1), "[]")
This line of code performs the following operations:
Alternative one-liners include:
strings.Trim(strings.Join(strings.Fields(fmt.Sprint(A)), delim), "[]")
strings.Trim(strings.Join(strings.Split(fmt.Sprint(A), " "), delim), "[]")
These variants employ different string manipulation methods to achieve the same result.
To incorporate a space after the delimiter, use arrayToString(A, ", ") or define the return statement as:
return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim + " ", -1), "[]")
The above is the detailed content of How to Convert a Go []int Slice to a Delimited String in One Line?. For more information, please follow other related articles on the PHP Chinese website!