I want to replace the nth char in the original string. I can access the nth char from the string by using chars[i]
, but when I assign a value to chars[i]
, I get an error.
package main
import "fmt"
func main() {
var chars = "abcdef"
fmt.Println(string(chars[3]))
chars[3] = "z" // is not working
}
Strings are immutable objects in go. So you cannot replace chars in a string. Instead you can create a new string using say slices with the replacement.
The strings package of Golang has a Replace() function which we can use to replace some characters in a string with a new value. It replaces only a specified "n" occurrences of the substring.
Replace() Function in Golang is used to return a copy of the given string with the first n non-overlapping instances of old replaced by new one. Here, s is the original or given string, old is the string that you want to replace. new is the string which replaces the old, and n is the number of times the old replaced.
In the following program ReplaceAllString() method is used, which allows us to replace original string with another string if the specified string matches with the specified regular expression.
Strings are immutable.
chars = chars[:3] + "z" + chars[4:]
This is happening because chars
is actually a string and is immutable. If you declared it appropriately (as a byte slice) then you can assign to it as you're attempting. Here's an example;
package main
import "fmt"
func main() {
var chars = []byte{'a', 'b', 'c', 'd', 'e', 'f'}
fmt.Println(string(chars[3]))
fmt.Printf("%T\n", chars)
chars[3] = 'z'
fmt.Println(string(chars))
}
https://play.golang.org/p/N1sSsfIBQY
Alternately you could use reslicing as demonstrated in the other answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With