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:Hellowill be replaced by thenew_string,Hi.
Return value
This function returns a new string.
package main//import packagesimport("fmt""strings")//program execution starts herefunc main(){//given input stringinputStr := "Hello from educative"//given old stringoldStr := "Hello"//given new stringnewStr := "Hi"//replace stringoutputStr := strings.ReplaceAll(inputStr, oldStr, newStr)//print the returned string after replace operationfmt.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
ReplaceAllfunction and assign the returned string tooutputStr.