Go Tutorial
Go Useful Resources
Selected Reading
- Go - 错误处理
- Go - Interfaces
- Go - 类型转换
- Go - 递归
- Go - Maps
- Go - 范围
- Go - 切片
- Go - 结构
- Go - 指针
- Go - 数组
- Go - 字符串
- Go - 作用域
- Go - 函数
- Go - 循环
- Go - 条件判断
- Go - 操作符
- Go - 常量
- Go - 变量
- Go - 数据类型
- Go - 基本语法
- Go - 程序结构
- Go - 环境设置
- Go - 概述
- Go - Home
Go Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Go - 字符串
Go - 字符串
在Go编程中广泛使用的字符串是只读字节片。在Go编程语言中,字符串是切片。Go平台提供了各种库来操作字符串。
统一码
正则表达式
串
unicode
regexp
strings
Creating Strings
创建字符串最直接的方法是写−
var greeting = "Hello world!"
每当编译器在代码中遇到字符串文字时,它都会创建一个字符串对象,其值在本例中为“Hello world!”。
字符串文字包含一个称为符文的有效UTF-8序列。字符串包含任意字节。
package main import "fmt" func main() { var greeting = "Hello world!" fmt.Printf("normal string: ") fmt.Printf("%s", greeting) fmt.Printf(" ") fmt.Printf("hex bytes: ") for i := 0; i < len(greeting); i++ { fmt.Printf("%x ", greeting[i]) } fmt.Printf(" ") const sampleText = "xbdxb2x3dxbcx20xe2x8cx98" /*q flag escapes unprintable characters, with + flag it escapses non-ascii characters as well to make output unambigous */ fmt.Printf("quoted string: ") fmt.Printf("%+q", sampleText) fmt.Printf(" ") }
This would produce the following result −
normal string: Hello world! hex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 quoted string: "xbdxb2=xbc u2318"
注意−字符串文字是不可变的,因此一旦创建它,就不能更改字符串文字。
String Length
len(str)方法返回字符串文字中包含的字节数。
package main import "fmt" func main() { var greeting = "Hello world!" fmt.Printf("String Length is: ") fmt.Println(len(greeting)) }
This would produce the following result −
String Length is : 12
Concatenating Strings
字符串包包括一个用于连接多个字符串的方法join−−
strings.Join(sample, " ")
Join将数组中的元素连接起来以创建单个字符串。第二个参数是seperator,它位于数组的元素之间。
让我们看看下面的例子-
package main import ("fmt" "math" )"fmt" "strings") func main() { greetings := []string{"Hello","world!"} fmt.Println(strings.Join(greetings, " ")) }
This would produce the following result −
Hello world!