Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace nth char from a string in Go

Tags:

string

replace

go

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
}
like image 475
Pankaj Khairnar Avatar asked Jun 07 '16 20:06

Pankaj Khairnar


People also ask

How do you replace a character in a string in Go?

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.

Can I change a specific character in a string in Golang?

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.

How do I replace text in Golang?

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.

How do I remove special characters from a string in Golang?

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.


2 Answers

Strings are immutable.

chars = chars[:3] + "z" + chars[4:]
like image 92
Darigaaz Avatar answered Sep 20 '22 13:09

Darigaaz


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.

like image 24
evanmcdonnal Avatar answered Sep 19 '22 13:09

evanmcdonnal