Home > Backend Development > Golang > Replace the last character in a string

Replace the last character in a string

PHPz
Release: 2024-02-09 10:54:19
forward
839 people have browsed it

Replace the last character in a string

php Xiaobian Youzi is here to introduce you to a useful string processing technique - replacing the last character in the string. In programming, sometimes we need to modify a string, and the last character is often the object that needs to be replaced. With some simple operations, we can easily implement this function. Next, we will introduce in detail how to use php to replace the last character in a string, let us learn together!

Question content

s=s[:len(s)-1] + "c"
Copy after login

I came across a problem that needed to be solved and I was surprised to find that there is no direct s[index] = "c" way (I guess this means the string is immutable?) .

Is the above the best way to replace the last character in a string?

Solution

Write a function suitable for UTF-8 encoded strings.

package main

import (
    "fmt"
    "unicode/utf8"
)

func replacelastrune(s string, new rune) string {
    old, size := utf8.decodelastruneinstring(s)
    if old == utf8.runeerror && size <= 1 {
        return s
    }
    return s[:len(s)-size] + string(new)
}

func main() {
    s := "hello worlΔ"
    fmt.println(s)
    s = replacelastrune(s, 'd')
    fmt.println(s)
}
Copy after login

https://www.php.cn/link/44fd3d54368ffe700c4d10c32fc61112

Hello WorlΔ
Hello World
Copy after login

The above is the detailed content of Replace the last character in a string. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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