2016-07-16 59 views
0

是否有任何類似的庫/包在模擬vis(3)unvis(3)爲BSD系統做的事情?我試圖做一些需要表示包含特殊字符(如空格等)的字符串。圖書館/包在去處理字符串編碼?

+0

辦[strconv.Quote(https://golang.org/pkg/strconv/#Quote)或QuoteToASCII你在找什麼? – hobbs

回答

0

不,不完全是,但如果你正在尋找URL編碼,你可以做你想做與net/url包中的所有URL編碼:
見:Encode/decode URLs
和:Is there any example and usage of url.QueryEscape ? for golang

示例代碼:

fmt.Println(url.QueryEscape("https://stackoverflow.com/questions/tagged/go test\r \r\n")) 

輸出:

http%3A%2F%2Fstackoverflow.com%2Fquestions%2Ftagged%2Fgo+test%0D+%0D%0A 

或寫自己:

圍棋串UTF-8編碼,實際上是個字節的只讀片:
你可能會得到字節是這樣的:

str := "UTF-8" 
bytes := []byte(str) // string to slice 
fmt.Println(str, bytes) // UTF8 [85 84 70 45 56] 

或轉換字節到這樣的字符串:

s := string([]byte{85, 84, 70, 45, 56, 32, 0xc2, 0xb5}) // slice to string 
fmt.Println(s)           // UTF-8 µ 

爲0xC2 0xB5執行是UTF-8(十六進制)用於字符 'MICRO SIGN'(U + 00B5)見:http://www.fileformat.info/info/unicode/char/00b5/index.htm

你也可能得到的字節是這樣的:

for i := 0; i < len(s); i++ { 
    fmt.Printf("%d: %d, ", i, s[i]) 
    //0: 85, 1: 84, 2: 70, 3: 45, 4: 56, 5: 32, 6: 194, 7: 181, 
} 

或緊湊十六進制格式:

fmt.Printf("% x\n", s) // 55 54 46 2d 38 20 c2 b5 

並獲得符文(Unicode代碼點)是這樣的:

for i, v := range s { 
    fmt.Printf("%d: %v, ", i, v) 
    //0: 85, 1: 84, 2: 70, 3: 45, 4: 56, 5: 32, 6: 181, 
} 

看:What is a rune?

和轉換符文字符串:符文

r := rune(181) 
fmt.Printf("%#U\n", r) // U+00B5 'µ' 
st := "this is UTF-8: " + string(r) 
fmt.Println(st) // this is UTF-8: µ 

轉換切片字符串:

rs := []rune{181, 181, 181, 181} 
sr := string(rs) 
fmt.Println(sr) // µµµµ 

字符串轉換爲切片符文:

br := []rune(sr) 
fmt.Println(br) //[181 181 181 181] 

的%Q(報價)動詞會轉義字符串中的任何不可打印的字節序列,因此輸出是明確的:

fmt.Printf("%+q \n", "Hello, 世界") // "Hello, \u4e16\u754c" 

unicode.IsSpace報告符文是否爲由Unicode的空白空間屬性定義的空格字符;在拉丁語-1空間這是

'\ t','\ n','\ v','\ f','\ r','',U + 0085(NEL),U + 00A0 (NBSP)。 示例代碼:

package main 

import (
    "bytes" 
    "fmt" 
    "unicode" 
) 

func main() { 
    var buf bytes.Buffer 
    s := "\u4e16\u754c \u0020\r\n 世界" 
    for _, r := range s { 
     if unicode.IsSpace(r) { 
      buf.WriteString(fmt.Sprintf("\\u%04x", r)) 
     } else { 
      buf.WriteString(string(r)) 
     } 
    } 
    st := buf.String() 
    fmt.Println(st) 
} 

輸出:

世界\u0020\u0020\u000d\u000a\u0020\u0020世界 

您可以在unicode/utf8unicodestrconvstrings包找到更多的功能:
https://golang.org/pkg/unicode/utf8/
https://golang.org/pkg/unicode/
https://golang.org/pkg/strings/
https://golang.org/pkg/strconv/

https://blog.golang.org/strings