Package strings implements simple functions to manipulate UTF-8 encoded strings. For information about UTF-8 strings in Go, see https://blog.golang.org/strings.
简单的utf-8编码的字符串操作库,详见:https://blog.golang.org/strings.
func clone
func Clone(s string) string
Clone 返回一个_s_
的拷贝, 当截取一个长字符串中的一部分时,确保s的拷贝是在新分配的内存中, 使用该方法可以帮助程序使用更少的内存, 由于使用clone会返回一个值拷贝, 过度使用Clone会让程序占用更多内存, 正常情况下应该尽量减少Clone的使用; 对于长度为0的字符串, 将返回_''_
,并且不分配内存空间.
package main
import (
"fmt"
"strings"
)
func main() {
var s string = "vito love golang"
sCloned := strings.Clone(s)
fmt.Println("s:\t\t", s, "&s\t\t", &s)
fmt.Println("sCloned:\t", sCloned, "&sCloned\t", &sCloned)
}
---------------------------------------------------------------------------------
Output:
s: vito love golang &s: 0xc000050250
sCloned:vito love golang &sCloned:0xc000050260
func Compare
func Compare(a, b string) int
比较两个字符串大小, 返回一个整数. 如果_a==b_
返回_0_
,若_a<b_
返回_-1_
,_a>b_
返回_1_
,
Compare只是用来和 bytes包对称, 比较字符串通常使用_==,>,<_
会更直观,更快.
package main
import (
"fmt"
"strings"
)
func main() {
var Words string = "go language" //2 bytes
var Letters string = "go" //1 bytes
var Chineses string = "你好" //6 bytes
fmt.Println(strings.Compare(Words, Letters)) //Words > Letters
fmt.Println(strings.Compare(Words, Chineses)) //Words < Chineses
fmt.Println(strings.Compare(Chineses, Letters)) //Chineses > Letters
fmt.Println(strings.Compare(Letters, Letters))
}
---------------------------------------------------------------------------------
Output:
1
-1
1
0
fun Contains
func Contains(s, substr string) bool
判断字符串s 是否包含字符串substr
package main
import (
"fmt"
"strings"
)
func main() {
substr := "go"
s := "golang"
substr2 := "java"
fmt.Println(strings.Contains(s, substr))
fmt.Println(strings.Contains(s, substr2))
}
---------------------------------------------------------------------------------
Output:
true
false