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的字符串, 将返回_''_,并且不分配内存空间.

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. var s string = "vito love golang"
  8. sCloned := strings.Clone(s)
  9. fmt.Println("s:\t\t", s, "&s\t\t", &s)
  10. fmt.Println("sCloned:\t", sCloned, "&sCloned\t", &sCloned)
  11. }
  12. ---------------------------------------------------------------------------------
  13. Output:
  14. s: vito love golang &s: 0xc000050250
  15. 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包对称, 比较字符串通常使用_==,>,<_会更直观,更快.

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. var Words string = "go language" //2 bytes
  8. var Letters string = "go" //1 bytes
  9. var Chineses string = "你好" //6 bytes
  10. fmt.Println(strings.Compare(Words, Letters)) //Words > Letters
  11. fmt.Println(strings.Compare(Words, Chineses)) //Words < Chineses
  12. fmt.Println(strings.Compare(Chineses, Letters)) //Chineses > Letters
  13. fmt.Println(strings.Compare(Letters, Letters))
  14. }
  15. ---------------------------------------------------------------------------------
  16. Output:
  17. 1
  18. -1
  19. 1
  20. 0

fun Contains

func Contains(s, substr string) bool
判断字符串s 是否包含字符串substr

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. substr := "go"
  8. s := "golang"
  9. substr2 := "java"
  10. fmt.Println(strings.Contains(s, substr))
  11. fmt.Println(strings.Contains(s, substr2))
  12. }
  13. ---------------------------------------------------------------------------------
  14. Output:
  15. true
  16. false