2015-11-05 77 views
0

Golang沒有php的strrchr函數。如果我想從這個字符串中刪除/path(包括最後一個斜槓),那麼在golang中怎麼做?修剪多個字符到右斜線,包括斜槓

mystr := "/this/is/my/path" 

所需的輸出

"/this/is/my" 

我能得到最後的斜槓的這樣

lastSlash := strings.LastIndex(mystr, "/") 

的索引,但我不知道如何創建一個新的字符串/path去除。怎麼做?

回答

3

captncraig的答案適用於任何類型的分隔符字符,但假設你是一個POSIX風格的機器上運行(「/」是路徑分隔符),什麼你操縱確實是路徑:

http://play.golang.org/p/oQbXTEhH30

package main 

import (
    "fmt" 
    "path/filepath" 
) 

func main() { 
    s := "/this/is/my/path" 
    fmt.Println(filepath.Dir(s)) 

    // Output: /this/is/my 
} 

從godoc(https://golang.org/pkg/path/filepath/#Dir):

迪爾返回所有,但路徑的最後一個元素,通常的路徑的目錄。刪除最後一個元素後,路徑將被清理,並刪除尾部的斜槓。

但如果你用/path運行它,它會返回/,這可能是也可能不是你想要的。

3

嘗試output := mystr[:strings.LastIndex(mystr, "/")]

mystr := "/this/is/my/path" 
idx := strings.LastIndex(mystr, "/") 
if idx != -1{ 
    mystr = mystr[:idx] 
} 

fmt.Println(mystr) 

playground link

0

以前的(非常令人滿意的)解決方案未涉及的一個拐角案例是尾隨/。即 - 如果你想/foo/bar/quux/修剪到/foo/bar而不是/foo/bar/quux

mystr := "/this/is/my/path/" 
trimpattern := regexp.MustCompile("^(.*?)/[^/]*/?$") 
newstr := trimpattern.ReplaceAllString(mystr, "$1") 

fmt.Println(newstr) 

這裏有一個更全面一點例如:http://play.golang.org/p/ii-svpbaHt

可與 regexp庫來完成