golang 基礎(18)字串

square-gopher.png
字串
- immutability 字串是不可變型別
- strigs 標準庫提供字串基本操作
- strconv 字串與其他型別的轉換
func main(){ var c byte = 'H' fmt.Println(c) mj := string(45) fmt.Println(mj) }
我們嘗試輸出 c byte = 'H'``和
string(45)``
72 -
結果可能預期有些差別,如果我們將```mj := string(72)``
我們就會得到
72 H
在 go 語言會將 sybmol(符號)看作數字,而將string是作為sybmole 的陣列
"hello world" 在 go 眼裡是陣列[72 101 100 108 111...],字元和數字之間的關係是 ASCII 定義的。
x := os.Args[1] y := os.Args[2] fmt.Println(x + y)
os.Args 會接受我們在執行 main.go 是命令列附加的引數
go run main.go 4 3
結果執行為 43 這是因為
x = "4"
所以輸出結果
那麼大家可能都會想到型別轉換,這樣進行轉換型別是行不通的
x := int(os.Args[1]) y := int(os.Args[2])
import( "fmt" "os" "strconv" )
- go 語言中提供了 strconv 用於型別轉換
mj := strconv.Itoa(45) fmt.Println(mj)
可以對剛才程式進行修改為來嘗試執行一下
x := strconv.Atoi(os.Args[1]) y := strconv.Atoi(os.Args[2]) fmt.Println(x + y)
.\main.go:15:19: multiple-value strconv.Atoi() in single-value context
這個很好理解也就是 strconv.Atoi
會返回兩個返回值,我們這裡只處理一個,需要對兩個返回值都進行處理。
x,err1 := strconv.Atoi(os.Args[1]) y,err2 := strconv.Atoi(os.Args[2]) if err1 != nil{ fmt.Println("Error converting first command line parameter!") os.Exit(1) } if err2 != nil{ fmt.Println("Error converting second command line parameter!") os.Exit(1) }
strings 標準庫為我們提供許多實用的方法
fmt.Println(strings.ToTitle("hello world"))
HELLO WORLD
fmt.Println(strings.Title("hello world"))
Hello World
fmt.Println(strings.Replace("Hello <NAME>","<NAME>","zidea",1))
Replace 方法很簡單
- 源字串
- 要替換內容
- 替換的內容
- 替換次數