2016-11-23 71 views
0

可能是一個愚蠢的事情,但就死在它有點...如何修整「[」從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) 
} 

// output: this[things]I would like to remove 

go playground

也試過所有這些,沒有成功:

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 

沒有工作。我在這裏錯過了什麼?

+2

https://golang.org/pkg/strings/#Replace –

回答

13

您錯過了閱讀文檔。 strings.Trim()

func Trim(s string, cutset string) string 

微調返回的字符串s與所有開頭和結尾包含在割去除 Unicode代碼點片。

在你輸入的字符[沒有處於領先也不尾隨位置,它在中間,所以strings.Trim() -being以及動作 - 將無法將其刪除。

嘗試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 
+0

不知怎的,我卻錯過了'領先和落後'的標準,謝謝 –