Go by Example 中文:字符串函數

Go by Example 中文:字符串函數

標準庫的 strings 包提供了很多有用的字符串相關的函數。這裏是一些用來讓你對這個包有個初步瞭解的例子。
對應的示例測試程序如下:

// Go by Example 中文:字符串函數
// https://books.studygolang.com/gobyexample/string-functions/
// 標準庫的 strings 包提供了很多有用的字符串相關的函數。這裏是一些用來讓你對這個包有個初步瞭解的例子。
package main

import s "strings"
import "fmt"

// 我們給 fmt.Println 一個短名字的別名,我們隨後將會經常用到。
var p = fmt.Println

/*
	這是一些 strings 中的函數例子。
	注意他們都是包中的函數,不是字符串對象自身的方法,
	這意味着我們需要考慮在調用時傳遞字符作爲第一個參數進行傳遞。
*/
func main() {
	p("Contains:	", s.Contains("test", "es"))
	p("Count:	", s.Count("test", "t"))
	p("HasPrefix:	", s.HasPrefix("test", "te"))
	p("HasSuffix:	", s.HasSuffix("test", "st"))
	p("Index:	", s.Index("test",	"e"))
	p("Join:	", s.Join([]string{"a", "b"}, "-"))
	p("Repeat:	", s.Repeat("a", 5))
	p("Replace:	", s.Replace("foo", "o", "0", -1))
	p("Replace:	", s.Replace("foo", "o", "0", 1))
	p("Split:	", s.Split("a-b-c-d-e", "-"))
	p("ToLower:	", s.ToLower("TEST"))
	p("ToUpper:	", s.ToUpper("test"))
	p()

	// 你可以在 [strings](http://golang.org/pkg/strings/)包文檔中找到更多的函數

	// 雖然不是 strings 的一部分,但是仍然值得一提的是獲取字符串長度和通過索引獲取一個字符的機制。
	p("Len:	", len("hello"))
	p("Char:", "hello"[1])
}

運行結果如下:

$ go run string-functions.go
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [a b c d e]
toLower:    test
ToUpper:    TEST
Len:  5
Char: 101

在VSCode中的運行結果截圖如下圖所示:
VSCode中的運行結果
下一個例子: 字符串格式化.

@mmcgrana 編寫 | everyx 翻譯 | 項目地址 | license

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章