2017-05-27 50 views
4

我在Golang中有一個字符串,它被引號包圍。我的目標是刪除側面的所有引號,但忽略字符串內部的所有引號。我應該如何去做這件事?我的直覺告訴我要像使用C#一樣使用RemoveAt函數,但我在Go中沒有看到類似的東西。如何刪除Golang中字符串的引號

例如:

"hello""world" 

應轉換爲:

hello""world 

對於進一步澄清,這:

"""hello""" 

將成爲這樣:

""hello"" 

因爲外部的只應該刪除。

回答

14

使用slice expression

s = s[1 : len(s)-1] 

如果有一種可能性,即在行情不存在,然後使用此:

if len(s) > 0 && s[0] == '"' { 
    s = s[1:] 
} 
if len(s) > 0 && s[len(s)-1] == '"' { 
    s = s[:len(s)-1] 
} 

playground example

2

您可以利用片去除切片的第一個也是最後一個元素。

package main 

import "fmt" 

func main() { 
    str := `"hello""world"` 

    if str[0] == '"' { 
     str = str[1:] 
    } 
    if i := len(str)-1; str[i] == '"' { 
     str = str[:i] 
    } 

    fmt.Println(str) 
} 

由於片段共享底層內存,因此不會複製字符串。它只是更改str切片以啓動一個字符,並更快結束一個字符。

這就是the various bytes.Trim functions的工作方式。

+0

此答案將數據複製兩次,一次在該字符串[]字節轉換和一旦在[]字節串轉換。 –

+0

@CeriseLimón謝謝,我仍然在學習字符串和[]字節之間的關係。我有一個頁面來解釋什麼時候會發生副本,什麼時候不會發生,但是我錯了。你有資源嗎? – Schwern

+1

字符串的支持數組是不可變的,而[]字節的支持數組是可變的。因此,在從一種類型轉換爲另一種類型時,必須複製支持數組。也就是說,在某些情況下,編譯器可以證明在字符串的生命週期內沒有對[]字節進行修改。在這些情況下,字符串將共享[]字節的後備數組。其中一種情況是使用[]字節在map [string] sometype:'m [string(p)]'中查找值。從轉換返回的字符串將與[]字節p共享後備數組。 –

2

使用slice expressions。您應該編寫可靠的代碼,爲不完整的輸入提供正確的輸出。例如,

package main 

import "fmt" 

func trimQuotes(s string) string { 
    if len(s) >= 2 { 
     if s[0] == '"' && s[len(s)-1] == '"' { 
      return s[1 : len(s)-1] 
     } 
    } 
    return s 
} 

func main() { 
    tests := []string{ 
     `"hello""world"`, 
     `"""hello"""`, 
     `"`, 
     `""`, 
     `"""`, 
     `goodbye"`, 
     `"goodbye"`, 
     `goodbye"`, 
     `good"bye`, 
    } 

    for _, test := range tests { 
     fmt.Printf("`%s` -> `%s`\n", test, trimQuotes(test)) 
    } 
} 

輸出:

`"hello""world"` -> `hello""world` 
`"""hello"""` -> `""hello""` 
`"` -> `"` 
`""` -> `` 
`"""` -> `"` 
`goodbye"` -> `goodbye"` 
`"goodbye"` -> `goodbye` 
`goodbye"` -> `goodbye"` 
`good"bye` -> `good"bye` 
相關問題