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
    }
}

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

查看所有标签

猜你喜欢:

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

人月神话(40周年中文纪念版)

人月神话(40周年中文纪念版)

(美) 布鲁克斯(Brooks, F. P.) 著 / UML China翻译组,汪颖 译 / 清华大学出版社 / 2015-4-1 / 68.00元

在软件领域,很少能有像《人月神话》一样具有深远影响力和畅销不衰的著作。Brooks博士为人们管理复杂项目提供了最具洞察力的见解,既有很多发人深省的观点,又有大量软件工程的实践。本书内容来自Brooks博士在IBM公司SYSTEM/360家族和OS/360中的项目管理经验,该项目堪称软件开发项目管理的典范。该书英文原版一经面世,即引起业内人士的强烈反响,后又译为德、法、日、俄、中、韩等多种文字,全球......一起来看看 《人月神话(40周年中文纪念版)》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具