Menu Close

Go – ReplaceAll() function in strings package in go

ReplaceAll() function in strings package is used to replace all matching string with another string in go.

strings.ReplaceAll() function returns a copy of the string s with all non-overlapping instances of old replaced by new string in go golang.

Function prototype:

func ReplaceAll(str, old, new string) 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

Return value:

ReplaceAll() function in strings package returns copy of the string with all non-overlapping instances of old replaced by new string.

Example with code:

package main

import (
  "fmt"
  "strings"
)

func main() {

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

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

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

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

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

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

Output:

EOo EOolang EO
EOo EOolang EO
EOo EOolang EO
EOo EOolang EO
o olang

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. Required fields are marked *