Home > Article > Backend Development > How to replace string in go language
In the Go language, you can use the Replace() function of the strings package to replace a string. The syntax is "strings.Replace(original string, value to be searched, replacement value, number of replacements)"; if you replace If the number of times is negative, it means that all specified substrings in the string will be replaced with new values.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
During the development process, sometimes we need to replace a specific string in a string with a new string. In the Go language, it is necessary to replace a certain string with a new string. Requirements, we can achieve it through the strings.Replace() function.
strings.Replace() function
Syntax
func Replace(s, old, new string, n int) string
Parameters | Description |
---|---|
s | The entire string to be replaced. |
old | The string to be replaced. What string should |
new | be replaced with. |
n | The number of times to be replaced, -1, then all old in the string s will be replaced with new. |
Return value
Returns the replaced string.
Explanation
Replace the old string in string s with the new string, replace n times, Returns the replaced string. If n is -1, then all old in string s will be replaced with new.
Usage example:
##Replace the string once
package main import ( "fmt" "strings" ) func main() { //使用 strings.Replace() 函数,替换字符串 strHaiCoder := "hello你好hello" fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", 1)) }
Replace string multiple times
package main import ( "fmt" "strings" ) func main() { //使用 strings.Replace() 函数,替换字符串 strHaiCoder := "hello你好hello" fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", 2)) }
Replace all strings
package main import ( "fmt" "strings" ) func main() { //使用 strings.Replace() 函数,替换字符串 strHaiCoder := "hello你好hello你好hello你好hello你好hello" fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", -1)) }【Related recommendations:
Go video tutorial, Programming teaching】
The above is the detailed content of How to replace string in go language. For more information, please follow other related articles on the PHP Chinese website!