英文:
How to Trim "[" char from a string in Golang
问题
可能是一个愚蠢的问题,但我卡在这上面有一段时间了...
无法从字符串中删除"["
字符,我尝试了以下几种方法,但都没有成功:
package main
import (
"fmt"
"strings"
)
func main() {
s := "this[things]I would like to remove"
t := strings.Trim(s, "[")
fmt.Printf("%s\n", t)
}
输出结果为:this[things]I would like to remove
我还尝试了以下所有方法,但都没有成功:
s := "this [ things]I would like to remove"
t := strings.Trim(s, " [ ")
// 输出结果为:this [ things]I would like to remove
s := "this [ things]I would like to remove"
t := strings.Trim(s, "[")
// 输出结果为:this [ things]I would like to remove
都没有起作用。我在这里漏掉了什么?
英文:
Probably a silly thing but got stuck on it for a bit...
Can't trim a "["
char from a string, things I tried with outputs:
package main
import (
"fmt"
"strings"
)
func main() {
s := "this[things]I would like to remove"
t := strings.Trim(s, "[")
fmt.Printf("%s\n", t)
}
// output: this[things]I would like to remove
Also tried all of those, with no success:
s := "this [ things]I would like to remove"
t := strings.Trim(s, " [ ")
// output: this [ things]I would like to remove
s := "this [ things]I would like to remove"
t := strings.Trim(s, "[")
// output: this [ things]I would like to remove
None worked. What am I missing here?
答案1
得分: 90
你错过了阅读文档。strings.Trim()
:
> func Trim(s string, cutset string) string
> Trim 函数返回字符串 s 的一个切片,其中移除了 cutset 中包含的所有前导和尾部的 Unicode 代码点。
你输入的 [
字符既不在前导位置,也不在尾部位置,而是在中间位置,所以 strings.Trim()
函数不会将其移除,这是其正常行为。
你可以尝试使用 strings.Replace()
替代:
s := "this[things]I would like to remove"
t := strings.Replace(s, "[", "", -1)
fmt.Printf("%s\n", t)
输出结果(在 Go Playground 上尝试):
thisthings]I would like to remove
此外,Go 1.12 中还添加了 strings.ReplaceAll()
函数(基本上是 Replace(s, old, new, -1)
的简写形式)。
英文:
You are missing reading the doc. strings.Trim()
:
> func Trim(s string, cutset string) string
> Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.
The [
character in your input is not in a leading nor in a trailing position, it is in the middle, so strings.Trim()
– being well behavior – will not remove it.
Try strings.Replace()
instead:
s := "this[things]I would like to remove"
t := strings.Replace(s, "[", "", -1)
fmt.Printf("%s\n", t)
Output (try it on the Go Playground):
thisthings]I would like to remove
There is also a strings.ReplaceAll()
added in Go 1.12 (which is basically a "shorthand" for Replace(s, old, new, -1)
).
答案2
得分: -4
试试这个
package main
import (
"fmt"
"strings"
)
func main() {
s := "this[things]I would like to remove"
t := strings.Index(s, "[")
fmt.Printf("%d\n", t)
fmt.Printf("%s\n", s[0:t])
}
英文:
Try this
package main
import (
"fmt"
"strings"
)
func main() {
s := "this[things]I would like to remove"
t := strings.Index(s, "[")
fmt.Printf("%d\n", t)
fmt.Printf("%s\n", s[0:t])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论