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

To remove a character from a string at a specific index in Go, you can convert the string to a slice of runes, remove the rune at the desired index, and then convert the slice back to a string.

Here's a function that takes a string s and an index i and returns the string with the character at the specified index removed:

main.go
func removeCharAtIndex(s string, i int) string {
    runes := []rune(s)
    return string(append(runes[:i], runes[i+1:]...))
}
127 chars
5 lines

For example, to remove the character at index 2 from the string "hello", you can call the function like this:

main.go
result := removeCharAtIndex("hello", 2)
fmt.Println(result) // prints "helo"
77 chars
3 lines

Note that this function only removes a single character at the specified index. If you want to remove multiple characters, you can modify the function to take the number of characters to remove as an argument and adjust the slice indices accordingly.

gistlibby LogSnag