18.1 字符串

(1)如何修改字符串中的一個字符:

str:="hello"
c:=[]byte(str)
c[0]='c'
s2:= string(c) // s2 == "cello"

(2)如何獲取字符串的子串:

substr := str[n:m]

(3)如何使用for或者for-range遍歷一個字符串:

// gives only the bytes:
for i:=0; i < len(str); i++ {
… = str[i]
}
// gives the Unicode characters:
for ix, ch := range str {
…
}

(4)如何獲取一個字符串的字節數:len(str)

如何獲取一個字符串的字符數:

最快速:utf8.RuneCountInString(str)

len([]int(str))

(5)如何連接字符串:

最快速: with a bytes.Buffer(參考章節7.2

Strings.Join()(參考章節4.7

使用+=

 str1 := "Hello " 
 str2 := "World!"
 str1 += str2 //str1 == "Hello World!"

(6)如何解析命令行參數:使用os或者flag

(參考例12.4

鏈接

results matching ""

    No results matching ""