Menu Close

Go – Replace() function in strings package in go

Here, Replace() function in strings package is used to replace n matching string with another string in go.

strings.Replace() function in strings package in go returns a copy of the string with the first given number of non-overlapping instances of old replaced by new string in go golang.

strings.Replace() function prototype:

func Replace(str, old, new string, n int) string

Input parameters:

str: String where operation will be performed.
old: String which is to be replaced with new string.
new: New string which will replace old string
n: Number of old strings to be replaced with new string

Return value:

Replace() function in strings package returns a copy of the string str with the first n  non-overlapping instances of old replaced by new. If n < 0, there is no limit on the number of replacements.

Example with code:

package main

import (
  "fmt"
  "strings"
)

func main() {

  s := strings.Replace("Go Golang G", "G", "EO", 2)
  fmt.Println(s)

  s = strings.Replace("Go Golang G", "G", "EO", -1)
  fmt.Println(s)

  s = strings.Replace("Go Golang G", "G", "EO", 1)
  fmt.Println(s)

  s = strings.Replace("Go Golang G", "G", "EO", 0)
  fmt.Println(s)

  s = strings.Replace("Go Golang G", "G", "", 2)
  fmt.Println(s)

  s = strings.Replace("Go Golang G", "", "EO", 1)
  fmt.Println(s)
  
}

Output:

EOo EOolang G
EOo EOolang EO 
EOo Golang G
Go Golang G
o olang G
EOGo Golang G

To learn more about golang, Please refer given below link:

References:

https://golang.org/pkg/

Posted in golang, strings

Leave a Reply

Your email address will not be published.

Contact Us