替换字符串中字符的第n个实例

I'm a bit new to Go, but I'm trying to replace every nth instance of my string with a comma. So for example, a part of my data looks as follows:

"2017-06-01T09:15:00+0530",1634.05,1635.95,1632.25,1632.25,769,"2017-06-01T09:16:00+0530",1632.25,1634.9,1631.65,1633.5,506,"2017-06-01T09:17:00+0530",1633.5,1639.95,1633.5,1638.4,991,

I want to replace every 6th comma with a ' ' so it looks like

"2017-06-01T09:15:00+0530",1634.05,1635.95,1632.25,1632.25,769"
"2017-06-01T09:16:00+0530",1632.25,1634.9,1631.65,1633.5,506"
"2017-06-01T09:17:00+0530",1633.5,1639.95,1633.5,1638.4,991"

I've looked at the regexp package and that just seems to be a finder. The strings package does have a replace but I don't know how to use it to replace specific indices. I also don't know how to find specific indices without going through the entire string character by character. I was wondering if there is a regEx solution that is more elegant than me writing a helper function. Strings are immutable so I'm not able to edit them in place.

EDIT: Cast the string into []bytes. This allows me to edit the string in place. Then the rest is a fairly simple for loop, where dat is the data.

So I figured out what I was doing wrong. I initially had the data as a string, but if I cast it to a byte[] then I can update it in place.

This allowed me to use a simple for loop below to solve the issue without relying on any other metric other than nth character instance

for i := 0; i < len(dat); i++ {
    if dat[i] == ',' {
        count += 1
    }
    if count%6 == 0 && dat[i] == ',' {
        dat[i] = '
'
        count = 0
    }

If that is your input, you should replace ," strings with ".You may use strings.Replace() for this. This will leave a last, trailing comma which you can remove with a slicing.

Solution:

in := `"2017-06-01T09:15:00+0530",1634.05,1635.95,1632.25,1632.25,769,"2017-06-01T09:16:00+0530",1632.25,1634.9,1631.65,1633.5,506,"2017-06-01T09:17:00+0530",1633.5,1639.95,1633.5,1638.4,991,`
out := strings.Replace(in, ",\"", "
\"", -1)
out = out[:len(out)-1]
fmt.Println(out)

Output is (try it on the Go Playground):

"2017-06-01T09:15:00+0530",1634.05,1635.95,1632.25,1632.25,769
"2017-06-01T09:16:00+0530",1632.25,1634.9,1631.65,1633.5,506
"2017-06-01T09:17:00+0530",1633.5,1639.95,1633.5,1638.4,991

If you want flexible.

package main

import (
    "fmt"
    "strings"
)

func main() {
    input := `"2017-06-01T09:15:00+0530",1634.05,1635.95,1632.25,1632.25,769,"2017-06-01T09:16:00+0530",1632.25,1634.9,1631.65,1633.5,506,"2017-06-01T09:17:00+0530",1633.5,1639.95,1633.5,1638.4,991,`
    var result []string

    for len(input) > 0 {
        token := strings.SplitN(input, ",", 7)
        s := strings.Join(token[0:6], ",")
        result = append(result, s)
        input = input[len(s):]
        input = strings.Trim(input, ",")
    }
    fmt.Println(result)
}

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