【问题标题】:Go test string contains substringGo 测试字符串包含子字符串
【发布时间】:2017-12-29 05:23:26
【问题描述】:

如何检查一个字符串是否是 Go 中另一个字符串的子字符串? 比如我要查someString.contains("something")

【问题讨论】:

    标签: go substring


    【解决方案1】:

    比较,有更多选择:

    import (
        "fmt"
        "regexp"
        "strings"
    )
    
    const (
        str    = "something"
        substr = "some"
    )
    
    // 1. Contains
    res := strings.Contains(str, substr)
    fmt.Println(res) // true
    
    // 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
    i := strings.Index(str, substr)
    fmt.Println(i) // 0
    
    // 3. Split by substr and check len of the slice, or length is 1 if substr is not present
    ss := strings.Split(str, substr)
    fmt.Println(len(ss)) // 2
    
    // 4. Check number of non-overlapping instances of substr in str
    c := strings.Count(str, substr)
    fmt.Println(c) // 1
    
    // 5. RegExp
    matched, _ := regexp.MatchString(substr, str)
    fmt.Println(matched) // true
    
    // 6. Compiled RegExp
    re = regexp.MustCompile(substr)
    res = re.MatchString(str)
    fmt.Println(res) // true
    

    基准: Contains 内部调用 Index,所以速度几乎相同(顺便说一句,Go 1.11.5 与 Go 1.14.3 相比差异更大)。

    BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
    BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
    BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
    BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
    BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
    BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op
    

    【讨论】:

      【解决方案2】:

      使用 strings 包中的函数 Contains

      import (
          "strings"
      )
      strings.Contains("something", "some") // true
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-11
        • 2016-11-20
        • 1970-01-01
        • 2020-11-03
        相关资源
        最近更新 更多