Home  >  Article  >  Backend Development  >  How to replace string in go language

How to replace string in go language

青灯夜游
青灯夜游Original
2023-01-10 17:17:157124browse

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.

How to replace string in go language

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))
}

How to replace string in go language

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))
}

How to replace string in go language

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))
}

How to replace string in go language

【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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn