替换字符串中的最后一个字符。

huangapple go评论165阅读模式
英文:

Replace the last character in a string

问题

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

我遇到了解决这个问题的需求,惊讶地发现没有直接的s[index] = "c"的方法(我猜这意味着字符串是不可变的?)。

上述的方法是替换字符串中最后一个字符的最佳方式吗?

英文:
  1. s=s[:len(s)-1] + "c"

I came across the need to solve this problem, and I was surprised to find out there is no direct s[index] = "c" way (I guess this means strings are immutable?).

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

答案1

得分: 3

请稍等,我会为您翻译代码部分。

  1. package main
  2. import (
  3. "fmt"
  4. "unicode/utf8"
  5. )
  6. func replaceLastRune(s string, new rune) string {
  7. old, size := utf8.DecodeLastRuneInString(s)
  8. if old == utf8.RuneError && size <= 1 {
  9. return s
  10. }
  11. return s[:len(s)-size] + string(new)
  12. }
  13. func main() {
  14. s := "Hello WorlΔ"
  15. fmt.Println(s)
  16. s = replaceLastRune(s, 'd')
  17. fmt.Println(s)
  18. }

请注意,这是一个用于处理UTF-8编码字符串的函数。它的作用是将字符串中的最后一个符文替换为指定的新符文。在main函数中,我们使用该函数将字符串s中的最后一个符文替换为字母'd',然后打印结果。

您可以在以下链接中查看代码的运行结果:https://go.dev/play/p/2LsSSS-5Y2l

英文:

Write a function that works for UTF-8 encoded strings.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;unicode/utf8&quot;
  5. )
  6. func replaceLastRune(s string, new rune) string {
  7. old, size := utf8.DecodeLastRuneInString(s)
  8. if old == utf8.RuneError &amp;&amp; size &lt;= 1 {
  9. return s
  10. }
  11. return s[:len(s)-size] + string(new)
  12. }
  13. func main() {
  14. s := &quot;Hello WorlΔ&quot;
  15. fmt.Println(s)
  16. s = replaceLastRune(s, &#39;d&#39;)
  17. fmt.Println(s)
  18. }

https://go.dev/play/p/2LsSSS-5Y2l

  1. Hello WorlΔ
  2. Hello World

答案2

得分: -4

使用正则表达式:

  1. regexp.MustCompile(".$").ReplaceAllString(s, "c")

查看实时演示

  1. s := "reli大"
  2. s = regexp.MustCompile(".$").ReplaceAllString(s, "c")
  3. println(s) // 输出 "relic"
英文:

Use regex:

  1. regexp.MustCompile(&quot;.$&quot;).ReplaceAllString(s, &quot;c&quot;)

See live demo

  1. s := &quot;reli大&quot;
  2. s = regexp.MustCompile(&quot;.$&quot;).ReplaceAllString(s, &quot;c&quot;)
  3. println(s) // prints &quot;relic&quot;

huangapple
  • 本文由 发表于 2023年4月14日 06:04:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76010194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定