一、字符串定义、长度、获取指定字节
package main import "fmt" func main() { str := "hello" fmt.Println(str) //获取字符串的长度 fmt.Println("字符串的长度:", len(str)) // 获取指定字节 fmt.Println("字节打印", str[0]) fmt.Printf("字符打印%c\n", str[0]) for i := 0; i < len(str); i++ { fmt.Printf("%c ", str[i]) } fmt.Println() for i, v := range str { fmt.Print(i, " ") fmt.Printf("%c ", v) fmt.Println() } }
hello 字符串的长度: 5 字节打印 104 字符打印h h e l l o 0 h 1 e 2 l 3 l 4 o
二、字符串与其他语言的区别
//go string默认为空串 func TestString(t *testing.T) { var s string t.Log("*" + s + "*") t.Log(len(s)) // 字符串空值判断 if s == "" { } if len(s) == 0 { } }
=== RUN TestString type_test.go:31: ** type_test.go:32: 0 --- PASS: TestString (0.00s) PASS
三、字符串分割、连接、转换
package string_func import ( "strconv" "strings" "testing" ) func TestStringFn(t *testing.T) { s := "A,B,C" //分割字符串 parts := strings.Split(s, ",") for _, part := range parts { t.Log(part) } //字符串链接 t.Log(strings.Join(parts, "-")) } //字符串转换 func TestConv(t *testing.T) { //整数转字符串 s := strconv.Itoa(10) t.Logf("s类型%[1]T,值%[1]s", s) t.Log("str" + s) num, _ := strconv.Atoi("10") //字符串转整数 t.Logf("num类型%[1]T,值%[1]d", num) }
=== RUN TestStringFn string_func_test.go:14: A string_func_test.go:14: B string_func_test.go:14: C string_func_test.go:17: A-B-C --- PASS: TestStringFn (0.00s) === RUN TestConv string_func_test.go:24: s类型string,值10 string_func_test.go:25: str10 string_func_test.go:28: num类型int,值10 --- PASS: TestConv (0.00s) PASS
四、补充
package string_test_test import "testing" func TestString(t *testing.T) { var s string s = "中" //长度为字节长度,编码为utf8 t.Log(len(s)) // 取出字符串中的utf8字符 c := []rune(s) t.Logf("c的长度%d,c的unicode%x", len(c), c[0]) } func TestSringToRune(t *testing.T) { s := "海晏河清" t.Logf("字符串长度%d", len(s)) t.Logf("utf8编码字符长度%d", len([]rune(s))) for _, e := range s { //格式化第一个参数 t.Logf("%[1]c %[1]d", e) } }
=== RUN TestString string_test.go:9: 3 string_test.go:12: c的长度1,c的unicode4e2d --- PASS: TestString (0.00s) === RUN TestSringToRune string_test.go:17: 字符串长度12 string_test.go:18: utf8编码字符长度4 string_test.go:21: 海 28023 string_test.go:21: 晏 26191 string_test.go:21: 河 27827 string_test.go:21: 清 28165 --- PASS: TestSringToRune (0.00s) PASS 进程 已完成,退出代码为 0