Junior
Is it possible to change a specific character in a string?
sobes.tech AI
Answer from AI
Strings in Go are immutable. You cannot directly change a single character in an existing string.
To get a modified string, you need to create a new one:
- Convert the string to a slice of runes (
[]rune). - Change the element in the slice.
- Convert the slice of runes back to a string.
// s - original string
s := "hello"
// Convert string to []rune
r := []rune(s)
// Change the rune at index
r[0] = 'ц' // replace 'h' with 'ц'
// Convert back to string
newString := string(r)
// newString will be "цеllo"
An alternative, less flexible but possible for simple cases, is string concatenation.
// s - original string
s := "hello"
// Create a new string by concatenating substrings and the desired character
newString := string(s[0]) + "ц" + s[2:] // example: change the second character
// newString will be "hцllo"