Go語言的字串轉換的處理一之strconv包
摘要:// code_028_strings_strconv project main.go
package main
import (
"fmt"
"strconv"
)
//strings和strconv包中的函式--->>>
//...
// code_028_strings_strconv project main.go package main import ( "fmt" "strconv" ) //strings和strconv包中的函式--->>> //strings包,字元處理:Contains,Join,Index,Repeat,Replace,Split,Trim, Fields //strconv包,字元轉換: //1) Append新增字串元素:AppendInt,AppednBool,AppendQuote, AppendQuoteRune //2) Format格式化程字串:FormatBool(false),FormatInt(1234, 10),FormatUint(12345, 10),Itoa(1023) //3) Parse字串轉換為其他型別:ParseBool("false"),ParseFloat("123.23", 64),ParseInt("1234", 10, 64),ParseUint("12345", 10, 64),Atoi("1023") //返回值value, err := strconv.ParseBool("false") func checkError(e error) { if e != nil { fmt.Println(e) } } func main() { //Append 系列函式將整數等轉換為字串後,新增到現有的位元組陣列中。 str := make([]byte, 0, 100) str = strconv.AppendInt(str, 4567, 10) //以10進位制方式追加 str = strconv.AppendBool(str, false) str = strconv.AppendQuote(str, "abcdefg") str = strconv.AppendQuoteRune(str, '單') fmt.Println(string(str)) //4567false"abcdefg"'單' // Format的使用 a2 := strconv.FormatBool(false) b2 := strconv.FormatInt(1234, 10) c2 := strconv.FormatUint(12345, 10) d2 := strconv.Itoa(1023) fmt.Println(a2, b2, c2, d2) //false 1234 12345 1023 //Parse的使用 a3, err := strconv.ParseBool("false") checkError(err) b3, err := strconv.ParseFloat("123.23", 64) checkError(err) c3, err := strconv.ParseInt("1234", 10, 64) checkError(err) d3, err := strconv.ParseUint("12345", 10, 64) checkError(err) e3, err := strconv.Atoi("1023") checkError(err) fmt.Println(a3, b3, c3, d3, e3) //false 123.23 1234 12345 1023 }