go语言学习2
字符串学习
/*
字符串是不可变的,这一点和c#/java是一样的
*/
//声明content变量为string类型
var content string
//给content变量赋值
content = "hello world"
fmt.Println(content)
//简写声明变量,并赋值
val := "val"
fmt.Println(val)
//字符串不支持直接修改
str := "hello go"
fmt.Printf("str type=%T str value=%s\n", str, str)
//通过下标获取,但不可以通过下标修改,编译是无法通过的
ch := str[0]
//打印ch类型和值
fmt.Printf("ch type=%T ch=%c\n", ch, ch)
//将字符串转换byte类型,就可以通过下标修改
byte1 := []byte(str)
//修改值
byte1[0] = 'c'
//byte1和上面ch变量类型适应的,byte等同于uint8,值区间为0 ~ 255
fmt.Printf("byte1 type=%T byte1 value=%s\n", byte1, byte1)
字符串拼接
package main // hello
import (
"bytes"
"fmt"
"strconv"
)
func main() {
//go语言字符串拼接 字符串拼接使用还是很频繁的
//方式一 和其他语言没有区别
str := ""
for i := 0; i < 10; i++ {
str += "hello\n"
}
fmt.Print(str)
//方式二 类似c#/Java的StringBuilder,拼接次数多的话,可以要使用的方式
var builder bytes.Buffer
for i := 0; i < 10; i++ {
//go语言,这一点和其他语言不一样.
//和字符串拼接的时候,int类型不会像c#/Java一样进行隐式类型转换
builder.WriteString("hello" + strconv.Itoa(i))
}
fmt.Println(builder.String())
}
秋风
2017-05-18