golang replace character

WBOY
Release: 2023-05-27 13:07:07
Original
879 people have browsed it

In golang, strings are immutable, which means that once a string is created, it cannot be modified on the original string and can only be modified by creating a new string.

If we want to replace certain characters in a string, there are usually two methods:

  1. Use the function ReplaceAll() in the strings package

The sample code is as follows:

import "strings"

func main() {
    str := "hello world"
    newStr := strings.ReplaceAll(str, "l", "x")
    fmt.Println(newStr) // 输出 hexxo worxd
}
Copy after login

In the above code, by introducing the strings package, the ReplaceAll() function is directly called to complete character replacement. The ReplaceAll() function will replace all matching items in string with the specified string.

  1. String slice splicing

The sample code is as follows:

func main() {
    str := "hello world"
    chars := []rune(str)
    for i := range chars {
        if chars[i] == 'l' {
            chars[i] = 'x'
        }
    }
    newStr := string(chars)
    fmt.Println(newStr) // 输出 hexxo worxd
}
Copy after login

In the above code, the string object is first converted into a rune array, and rune represents Unicode character, and the rune array is the representation of the string in memory. Then it traverses the rune array, replaces it by judging whether the character is equal to 'l', and finally obtains the replaced string by converting the rune array back to string.

Overall, the second method is more flexible. You can use a for loop to traverse each character in the string and perform more fine-grained operations, such as replacing only certain characters. The first method abstracts the replacement logic into a function, which is simpler and more convenient to use. Just choose different methods based on actual needs.

The above is the detailed content of golang replace character. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
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!