Use the strings.Replace function to replace a substring in a string

WBOY
Release: 2023-07-24 22:01:44
Original
1371 people have browsed it

Use the strings.Replace function to replace a substring in a string

In the Go language, the strings.Replace function can be used to replace a specific substring in a string. This function has four parameters, namely the original string, the old substring, the new substring and the number of substitutions. Below we will demonstrate how to use this function through an example.

First, we need to import thestringspackage:

import "strings"
Copy after login

Code example: Replace substrings in strings

package main import ( "fmt" "strings" ) func main() { str := "hello, hello, hello" old := "hello" new := "goodbye" count := 2 result := strings.Replace(str, old, new, count) fmt.Println(result) }
Copy after login

In this example, we A stringstris created, which contains three consecutive "hello" substrings. We want to replace the first two "hello"s with "goodbye". Using thestrings.Replacefunction, we set the old substring to "hello", the new substring to "goodbye", and the number of replacements to 2. The result will be saved in the variableresult.

Finally, we observe the replaced string by printingresult.

Run the above code, the output result is:

goodbye, goodbye, hello
Copy after login

We can see that the function successfully replaced the first two "hello", but the third "hello" was not replaced.

Summary

Use thestrings.Replacefunction to easily replace substrings in a string. The four parameters of this function are the original string, the old substring, the new substring and the number of substitutions. By setting appropriate parameters, we can implement string replacement operations.

The above is an introduction to using the strings.Replace function to replace substrings in a string. I hope it will be helpful to you!

The above is the detailed content of Use the strings.Replace function to replace a substring in a string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!