go語言常用的系統字串函式筆記

2021-10-07 08:04:29 字數 2752 閱讀 8381

str :=

"hello北京"

str2 :=

rune

(str)

for i :=

0; i <

len(str2)

; i++

// 字串轉整數

n, err := strconv.

atoi

("123"

)if err !=

nilelse

// 整數轉字串

str := strconv.

itoa

(12345

)

var bytes =

byte

("hello go"

)fmt.

printf

("bytes= %v\n"

, bytes)

str =

string([

]byte

)fmt.

println

(str)

str = strconv.

formatint

(123,2

)str = strconv.

formatint

(123,8

)str = strconv.

formatint

(123,16

)

b := strings.

contains

("asdfggg"

,"ggg"

)// 返回bool型

fmt.

println

(b)

num := strings.

count

("aaabbb"

,"a"

)//返回int型

fmt.

println

(num)

b := strings.

equalfold

("abc"

,"abc"

)// 返回true

fmt.

println

(b)

index := strings.

index

("abcdef"

,"ef"

)// 如果找不到就返回-1

fmt.

println

(index)

index := strings.

lastindex

("go golang"

,"go"

)// 如果沒有返回-1

fmt.

println

(index)

str :=

"go go hello"

str = strings.

replace

(str2,

"go"

,"hello",-

1)// -1代表全部替換,可以指定其他數字替換數目

fmt.

println

(str)

strarr := strings.

split

("hello world ok"

," "

)for i :=

0; i <

len(strarr)

; i++

str :=

"golang hello"

str = strings.

tolower

(str)

fmt.

println

(str)

str = strings.

toupper

(str)

fmt.

println

(str)

str := strings.

trimspace

(" n b c "

)fmt.

println

(str)

str := strings.

trim

("! hello !"

,"!"

)str := strings.

trimleft

("! hello !"

,"!"

)// 去除左邊

str := strings.

trimright

("! hello !"

,"!"

)// 去除右邊

fmt.

println

(str)

b := strings.

hasprefix

("abdme"

,"ab"

)fmt.

println

(b)// true

b := strings.

hassuffix

("abcme"

,"me"

)fmt.

println

(b)// true

Go字串常用函式

一 統計字串長度,按位元組算,len string 二 字串遍歷,同時處理中文編碼問題。三 字串轉數字,字串轉bool值等等,略,已在前面講過。四 字串查詢,strings.contains 由下圖可知,strings.contains 判斷的結果為返回bool值。五 字串統計,strings.co...

C語言字串讀入函式筆記

gets str 函式和scanf s str 區別 二者都是從終端讀入字串。功能為 1 gets功能為讀入一行,並將換行符轉換為字串結束符。2 scanf s s 讀入時,遇到空白字元,包括空格,製表符,換行符時均會停止輸入。從功能上可以看出不同之處 1 終止條件不同。gets只有遇到 n時才會結...

Go字串函式

下面的 中,列出了go官方包中常見的字串函式。package main import s strings import fmt 為列印函式起個小名兒,比較有特點的用法 var p fmt.println func main 用 把陣列拼接成字串p repeat s.repeat a 5 重複5次p ...