golang 常用代碼

1. 字符串常見方法

1.1 字符串三種比較方法

fmt.Println("go"=="go")
fmt.Println("GO"=="go")

fmt.Println(strings.Compare("GO","go"))
fmt.Println(strings.Compare("go","go"))

fmt.Println(strings.EqualFold("GO","go"))

輸出

true
false
-1
0
true

1.2 字符串替換

//替換的字符串爲 dstpathtmp,把 dstpathtmp[comma:]替換爲"", -1代表全部替換,替換次數
var dstpathtmp_no_module = strings.Replace(dstpathtmp, dstpathtmp[comma:], "", -1)

1.3 字符串截取

//Index 順着查找,LastIndex倒着查找,返回comma是座標
comma := strings.LastIndex(dstpathtmp, "/")

//module name : dstpathtmp[comma+1:]
//fmt.Println("result1", dstpathtmp[comma+1:])

結果:
    dstpathtmp如果爲system/lib/binderxxx,那麼
    dstpathtmp[comma:]/binderxxx 
    dstpathtmp[comma+1:] 爲binderxxx

1.4 字符串包含

var s string = "hello go"
//判斷字符串s是否包含子串
r := strings.Contains(s, "go")
fmt.Println(r) //true

1.5 串聯

//返回count個s串聯的字符串
s3 := strings.Repeat(s, 2)
fmt.Println(s3) //hello gohello go

1.6 按空格返回切片數組

//去除字符串的空格符,並且按照空格分割返回slice
s7 := " hello go "
s8 := strings.Fields(s7)
fmt.Println(s8) //[hello go]

1.7 去除兩端字符

//切除字符串兩端的某類字符串
s6 := strings.Trim(s, "o")
fmt.Println(s6) //hello g

2. 函數

2.1 函數定義和調用

func CheckFileContainsStr(filepath ,str string) bool {
    ...
	return false
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章