Go -- 字符串

栏目: Go · 发布时间: 6年前

内容简介:Unicode是一种常用的字符串函数包:strings和strconv
  1. string是数据类型, 不是引用或指针类型
  2. string是 只读的byte slice ,len()返回它所包含的 byte数 (并不等同于 字符数
  3. string的byte数组可以存放 任何数据
func TestStringBasic(t *testing.T) {
    var s string
    t.Log(s) // 初始化为默认零值“”

    s = "hello"
    t.Log(len(s)) // 5

    // string是不可变的byte slice
    // s[1] = '3' // cannot assign to s[1]

    // 可以存储任何二进制数据
    s = "\xE4\xB8\xAD"
    t.Log(s) // 中
}

编码与存储

Unicode是一种 字符集 (code point,字符编码),UTF-8是Unicode的 存储实现 (转换为 字节序列 的规则)

func TestStringEncode(t *testing.T) {
    s := "中"
	t.Log(len(s)) // 3,byte数

	// rune:取出string中的Unicode
	c := []rune(s)
	t.Log(len(c))                    // 1
	t.Log(unsafe.Sizeof(c[0]))       // 4
	t.Logf("%s Unicode %X", s, c[0]) // 中 Unicode 4E2D
	t.Logf("%s UTF-8 %X", s, s)      // 中 UTF-8 E4B8AD
}

func TestStringToRune(t *testing.T) {
    s := "中山市"
    // range遍历,迭代输出的是rune,而不是byte
    for _, c := range s {
    	// [1]表示都格式化第1个参数
    	t.Logf("%[1]c %[1]X", c)
    	// 中 4E2D
    	// 山 5C71
    	// 市 5E02
    }
}
字符 “中”
Unicode 0x4E2D
UTF-8 0xE4B8AD
string/[]byte [0xE4,0xB8,0xAD]

字符串函数

常用的字符串函数包:strings和strconv

import (
    "strconv"
    "strings"
    "testing"
)

func TestStrings(t *testing.T) {
    s := "A,B,C"
    // 分割
    parts := strings.Split(s, ",")
    for _, part := range parts {
    	t.Log(part)
    }
    // 连接
    t.Log(strings.Join(parts, "-")) // A-B-C
}

func TestStringConvert(t *testing.T) {
    s := strconv.Itoa(10)
    t.Log("str" + s) // str10,Go不支持隐式转换,证明10是字符串
    if i, err := strconv.Atoi("10"); err == nil {
    	t.Log(10 + i) // 20
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Flash ActionScript 3.0 动画高级教程

Flash ActionScript 3.0 动画高级教程

Keith Peters / 苏金国、荆涛 / 人民邮电出版社 / 2010-1 / 65.00元

《Flash ActionScript 3.0 动画高级教程》是介绍Flash 10 ActionScript动画高级技术的经典之作,是作者在这一领域中多年实践经验的结晶。书中不仅涵盖了3D、最新绘图API以及Pixel Bender等Flash 10 ActionScript特性,深入介绍了碰撞检测、转向、寻路等Flash游戏开发技术,还通过实例具体讲解了等角投影和数值积分的基本理论和应用。 ......一起来看看 《Flash ActionScript 3.0 动画高级教程》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换