Home >Backend Development >Golang >How to Convert a Go []int Slice to a Delimited String in One Line?

How to Convert a Go []int Slice to a Delimited String in One Line?

DDD
DDDOriginal
2024-12-06 22:26:15324browse

How to Convert a Go []int Slice to a Delimited String in One Line?

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:

  1. Uses fmt.Sprint(A) to convert the slice to a string.
  2. Replaces spaces in the string with the specified delimiter using strings.Replace(..., delim, -1). The -1 parameter ensures replacements throughout the string.
  3. Strips leading and trailing square brackets using strings.Trim(...).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn