8

Most programming languages have a function that allows us to insert one string into another string. For example, I can take the string Green and the string HI, and perform an operation Green.insert(HI,2) to get the resulatant string GrHIeen. But such a function does not come with the standard GO lang library.

Is there any Golang function which I can use to insert a string inside an string?

For example

string = "</table></body></html>"

// I want Following Output

string = "</table><pagebreak /></body></html>"
Ali
  • 306
  • 2
  • 5
  • 18
  • See [Golang: format a string without printing?](http://stackoverflow.com/a/31742265/1705598) – icza Oct 04 '16 at 01:17
  • Would a template fit better here? https://golang.org/pkg/text/template/#example_Template – Sairam Oct 06 '16 at 18:17
  • If you're handling HTML, though, you should consider using a [DOM](https://godoc.org/honnef.co/go/js/dom) so that way the opening/closing tags, attributes, etc. are all _automatically_ correct. – Alexis Wilke Jul 27 '20 at 18:39

3 Answers3

15

You can simply use slice operations on the string:

package main

func main() {
    p := "green"
    index := 2
    q := p[:index] + "HI" + p[index:]
    fmt.Println(p, q)
}

Working example: https://play.golang.org/p/01phuBKuBB

abhink
  • 6,919
  • 1
  • 25
  • 38
2

You could turn the first string into a template for Sprintf. It would look like this:

p := "</table>%s</body></html>"
out := fmt.Sprintf(p,"<pagebreak />")

Working code here: https://play.golang.org/p/AInfyQwpy2

Liam Kelly
  • 2,826
  • 1
  • 14
  • 25
0

I had used rune and bytes.Buffer to insert <\b> bold tags at between two indexes and build a result string as below.

for j:=0; j< len(resultstrIntervals);j++{

        startIndex:= resultstrIntervals[j].Start
        endIndex:= resultstrIntervals[j].End

        for i <= endIndex && i <= len(s) {

            if i == startIndex{
                buffer.WriteRune('<')
                buffer.WriteRune('b')
                buffer.WriteRune('>')


            }else if i == endIndex{

                buffer.WriteRune('<')
                buffer.WriteRune('/')
                buffer.WriteRune('b')
                buffer.WriteRune('>')

            }
            if i < len(strArr){
                buffer.WriteRune(strArr[i])
            }
            i++

        }

    }
    fmt.Print(buffer.String())

example

Amogh Antarkar
  • 109
  • 1
  • 13