remove a substring from a string at a specific index in go

To remove a substring from a string at a specific index in Go, you can use string concatenation and substrings manipulation. Here's an example:

main.go
func removeSubstringAtIndex(s string, idx int, substr string) string {
    if idx < 0 || idx >= len(s) {
        return s
    }
    return s[:idx] + strings.Replace(s[idx:], substr, "", 1)
}

// Example usage
s := "this is a test string"
idx := 8
substr := "a "
result := removeSubstringAtIndex(s, idx, substr)
fmt.Println(result) // Output: "this is test string"
364 chars
14 lines

In this example, we define a function removeSubstringAtIndex that takes in a string s, an integer index idx, and a substring substr. The function checks if the index is within range of the input string and returns s if it's out of bounds.

If the index is valid, the function concatenates the substring before the index s[:idx] with the truncated string after the index where the substring to be removed will be replaced by an empty string strings.Replace(s[idx:], substr, "", 1). The 1 parameter in Replace specifies the maximum number of replacements to be made.

We then test this function by passing in an example s, idx, and substr values and print the resulting string to the console.

gistlibby LogSnag