insert a string into another string at a specific index in go

To insert a string into another string at a specific index in Go, you can use string concatenation and indexing.

main.go
str := "Hello World"
insertStr := " beautiful"
index := 5

// concatenate the substrings before and after the index with the string to insert
resultStr := str[:index] + insertStr + str[index:]

fmt.Println(resultStr) // "Hello beautiful World"
244 chars
9 lines

In this example, we first define the main string str, the string we want to insert insertStr, and the index where we want to insert the substring index.

We then concatenate the substring of the main string before the index (str[:index]), the string we want to insert (insertStr), and the substring of the main string after the index (str[index:]) using the + operator and assign it to a new string variable resultStr.

The resulting string resultStr will contain the original string with the new substring inserted at the specified index.

gistlibby LogSnag