0

Using the following as a starting point I was able to get something working.

How to insert a Character every X Characters in a String in Golang?

But I want to know if there is an idiomatic way to write golang for what I wan to do, which is the output of the first fmt.Println shown below:
package main

import (
    "bytes"
    "fmt"
)

func insertStringInto(s string, interval int, sep string) string {
    var buffer bytes.Buffer
    before := interval - 1
    last := len(s) - 1
    for i, char := range s {
        buffer.WriteRune(char)
        if i%interval == before && i != last {
            buffer.WriteString(sep)
        }
    }
    return buffer.String()
}


func main() {
    fmt.Println("0x" + insertStringInto("01234567891011121314151617181920", 2, ", 0x"))

    fmt.Println(insertStringInto("01234567891011121314151617181920", 2, ", 0x"))
}

Produces the following:

0x01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20
01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20

Link to play.golang.org below:

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

2 Answers2

1

I'm not sure how idiomatic this is but re-slicing of strings is often used for this sort of thing. Also strings.builder was introduced recently.

func insertInto(s string, interval int, prefix, sep string) string {
    sb := strings.Builder{}
    sb.Grow((len(s)/interval+1)*(interval+len(prefix)+len(sep)))

    first := true
    for i := 0; i < len(s)/interval; i++ {
        if first {
            first = false
        } else {
            sb.WriteString(sep)
        }
        sb.WriteString(prefix)
        sb.WriteString(s[i*interval :(i+1)*interval])
    }
    return sb.String()
}

...
    print(insertInto("0123456789101112131415161718192", 2, "0x", ", "))

Note that this does not try to validate that the string only contains hex digits. It also assumes that it is a multiple of interval, but could be easily tweaked.

Andrew W. Phillips
  • 3,254
  • 1
  • 21
  • 24
0

You can use regex

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func AnotherWay(s string, after int, sep string) string {
    ex, _ := regexp.Compile(`([0-9]{2})`)
    return strings.TrimSuffix(ex.ReplaceAllString(s, sep+"$1, "), ", ")
}

func main() {
    fmt.Println(AnotherWay("01234567891011121314151617181920", 2, "0x"))
}
Lucas Katayama
  • 4,445
  • 27
  • 34