In the realm of programming, there often lies a need to convert a collection of integers into a delimited string. Consider an array of integers []int{1, 2, 3} that you desire to express as "1, 2, 3" with a customizable delimiter. While Python and Go provide eloquent built-in solutions, this article explores an elegant one-liner that can achieve the transformation effortlessly in Go.
First, a utility function arrayToString is defined to serve the conversion purpose. This function takes an array of integers and a delimiter as parameters and returns the desired string.
func arrayToString(a []int, delim string) string { return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim, -1), "[]") }
The core of the conversion lies within the strings.Trim and strings.Replace functions. fmt.Sprint(a) converts the array to a string, which is then modified by replacing " " (space character) with the desired delimiter. The -1 argument in Replace ensures all occurrences of space are replaced. Finally, strings.Trim removes any leading or trailing "[]" characters that may arise from the original array.
The arrayToString function empowers you to convert arrays of integers to strings with varying delimiters. For instance, the code:
A := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println(arrayToString(A, ", ")) // Output: "1, 2, 3, 4, 5, 6, 7, 8, 9" fmt.Println(arrayToString(A, ", ")) // Output: "1, 2, 3, 4, 5, 6, 7, 8, 9" fmt.Println(arrayToString(A, ";")) // Output: "1; 2; 3; 4; 5; 6; 7; 8; 9"
demonstrates the flexibility of the conversion, producing strings with different delimiters based on the input.
If you prefer to include a space after the delimiter, you can enhance the arrayToString function as follows:
func arrayToString(a []int, delim string) string { return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim + " ", -1), "[]") }
This addition ensures that a space is inserted after each delimiter in the output string.
By harnessing the power of strings.Trim and strings.Replace functions, our one-liner efficiently transforms an array of integers into a delimited string in Go. This technique provides versatility in delimiters and allows for customization in output formatting, making it a valuable tool for various string manipulation tasks.
The above is the detailed content of How to Convert an Array of Integers to a Delimited String in Go using a One-Liner?. For more information, please follow other related articles on the PHP Chinese website!