Junior
Is it possible to change a specific character in a string?
sobes.tech AI
Answer from AI
In Go, strings are immutable. To change a character, you need to create a new string. This can be done by converting the string into a byte slice or rune slice, modifying the desired element, and then converting it back to a string.
Example with a byte slice:
// Original string
s := "hello"
// Convert to byte slice
b := []byte(s)
// Change the character
b[0] = 'H'
// Convert back to string
newS := string(b)
// newS is now "Hello"
Example with a rune slice (for working with Unicode characters):
// Original string with Unicode characters
s := "привет"
// Convert to rune slice
r := []rune(s)
// Change the character
r[0] = 'П'
// Convert back to string
newS := string(r)
// newS is now "Привет"
Using a rune slice is preferable for correct handling of multi-byte Unicode characters.