How to replace characters in a Go string

Overview

In this shot, we’ll learn about how to replace characters in Golang. We can replace characters in a string using the ReplaceAll() function provided by the strings package.

Syntax

strings.ReplaceAll(string_input, old_string, new_string)

Parameters

  • string_input: This is the given input string, Hello from educative.
  • old_string: Hello will be replaced by the new_string, Hi.

Return value

This function returns a new string.

package main
//import packages
import(
"fmt"
"strings"
)
//program execution starts here
func main(){
//given input string
inputStr := "Hello from educative"
//given old string
oldStr := "Hello"
//given new string
newStr := "Hi"
//replace string
outputStr := strings.ReplaceAll(inputStr, oldStr, newStr)
//print the returned string after replace operation
fmt.Println(outputStr)
}

Explanation

In the code snippet above,

  • Line 12: We provide the input string.
  • Line 15: We provide the old string that will be replaced by the new string in line 18.
  • Line 21: We replace the string or characters using the ReplaceAll function and assign the returned string to outputStr.

Free Resources