简体   繁体   中英

How to insert a string inside another string using Go lang

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>"

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM