Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int array to string separated by ','

Tags:

go

I know that for string array []string I can use strings.Join(a []string, ',') but I want to do the same thing for an integer array []int.

My usecase is something like this for a query where variants is []map[string]int

 var Ids []int
    sqlStr := "select id from mapping where my_id in ("
    for _, mp := range variants {
       sqlStr += "?,"
       Ids = append(Ids, mp["id"])
    }
    sqlStr = strings.TrimRight(sqlStr, ",")
    rows, err := db.Query(sqlStr+")", strings.Join(Ids, ',')) // I can't do this because Join needs String array

How to achieve this?

like image 921
Jagrati Avatar asked Sep 20 '16 13:09

Jagrati


People also ask

How do you get a comma separated string from an array in C?

Use string join() function to get the comma separated strings.

How do you make an array into a string?

Below are the various methods to convert an Array to String in Java: Arrays. toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array.

How do you convert a comma separated string to an array?

The split() method is used to split a string on the basis of a separator. This separator could be defined as a comma to separate the string whenever a comma is encountered. This method returns an array of strings that are separated.


3 Answers

Make IDs a []string and convert the integers when you append them

var IDs []string
for _, i := range []int{1, 2, 3, 4} {
    IDs = append(IDs, strconv.Itoa(i))
}

fmt.Println(strings.Join(IDs, ", "))

https://play.golang.org/p/xrfuMRjgiI

like image 183
JimB Avatar answered Sep 29 '22 13:09

JimB


I would prefer to use json.Marshal. It is much simple and easy to use.

data := []int{100, 200, 300}
s, _ := json.Marshal(data)

fmt.Println(strings.Trim(string(s), "[]"))

GoPlaygroundLink

I hope this helps you. Please feel free to ask in case of doubts. WebsiteLink

like image 30
yogesh_desai Avatar answered Sep 29 '22 11:09

yogesh_desai


Here is an efficient way to do that:

func sqlIntSeq(ns []int) string {
    if len(ns) == 0 {
        return ""
    }

    // Appr. 3 chars per num plus the comma.
    estimate := len(ns) * 4
    b := make([]byte, 0, estimate)
    // Or simply
    //   b := []byte{}
    for _, n := range ns {
        b = strconv.AppendInt(b, int64(n), 10)
        b = append(b, ',')
    }
    b = b[:len(b)-1]
    return string(b)
}

You can use it in the SQL queries like that:

query := `SELECT * FROM table WHERE id IN (` + sqlIntSeq(ids) + `)`

Playground: https://play.golang.org/p/zi7YYetGu7.

like image 22
Ainar-G Avatar answered Sep 29 '22 11:09

Ainar-G