golang之字串操作

2021-08-28 01:20:27 字數 1101 閱讀 9875

1.字串在另乙個字串第一次出現的位置

str := "hello world"

fmt.println(strings.index(str, "world")) //6

2.字串在另乙個字串最後一次出現的位置

fmt.println(strings.lastindex(str, "l"))   //9
3.切割字串

fmt.println(strings.split(str, "l"))     // [he  o wor d]
4.字串陣列轉化為字串

list := string;

fmt.println(strings.join(list, "-")) // he-o-word

5.字串是否已另乙個字串開始或者結束

fmt.println(strings.hasprefix(str, "hello"))   //true

fmt.println(strings.hassuffix(str, "hello")) //false

6.字串大小寫轉化

fmt.println(strings.toupper(str))    //hello world

fmt.println(strings.tolower(str)) //hello world

7.刪除收尾特定字串

fmt.println(strings.trim(str, "h"))    //ello world
8.刪除收尾空格

fmt.println(strings.trimspace(str))   //hello world
9.字串替換

fmt.println(strings.replace(str, "hello", "your", -1))    //your world
將str的字串裡的hello替換為your, 第四個引數為替換次數,-1為全部替換

golang 字串操作例項

package main import s strings import fmt var p fmt.println func main 字串陣列 連線 a b p repeat s.repeat a 5 重複乙個字串 aaaaa p replace s.replace foo o 0 1 字串替換...

Golang 字串型別和字串操作

package main import fmt func main 標準輸出 bo y 我來自 t中國package main import fmt func main 標準輸出 我叫boy false true true true false false truepackage main impo...

golang對字串的操作

字串操作在程式設計中佔了很大的比重。package main import bytes fmt strconv strings unicode 簡單實用string操作符 func contains s,substr string bool func join a string,sep string...