问题
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
}
回答1:
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.
回答2:
Strings are immutable.
chars = chars[:3] + "z" + chars[4:]
回答3:
Use slice indexing to remove the character at the index, and place a new character there instead.
package main
import "fmt"
func main() {
var chars = "abcdef"
fmt.Println(string(chars[3]))
chars = chars[:3] + "z" + chars[3+1:]
fmt.Println(string(chars[3]))
}
Output:
d
z
[:3]
selects everything in the slice from the beginning up until the index 3, and [3+1:] selects everything from the index (3+1) until the end of the slice. Put the character you wanted in-between the two statements and cat them all together for the effect of replacing a character at a specific index.
If you want to replace a specific character (i.e. all (or some of) the instances of the letter 'b') you can use the strings.Replace function.
来源:https://stackoverflow.com/questions/37688457/how-to-replace-nth-char-from-a-string-in-go