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

Replace the last character in a string

PHPz
PHPzforward
2024-02-09 10:54:19795browse

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"

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

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

Hello WorlΔ
Hello World

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete