30

golang 基础(18)字符串

 5 years ago
source link: https://studygolang.com/articles/19221?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
U3IrMnj.png!web

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 方法很简单

  • 源字符串
  • 要替换内容
  • 替换的内容
  • 替换次数

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK