Use the function Contains from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
Answer from Elliott Beach on Stack OverflowUse the function Contains from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
To compare, there are more options:
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
Benchmarks:
Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on 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
Does strings.Contains use regex?
Is strings.Contains case-sensitive?
What does strings.Contains(s, "") return?
Videos
Hello, I've recently encountered an issue trying to use the strings.Contains( ) function after pulling values into an interface from a SQLite database. I am able to successfully use the converted string to print out its contents and set other variables but for some reason the strings.Contains() function doesn't like it. My question is what am I doing wrong and what would be the best way to go about verifying the content of the data pulled from the database?
Any and all help or criticism would be greatly appreciated! Thanks!
Snippet Here:
rows, err := db.Query(stmt)
if err != nil {
log.Println(err, stmt, dbpath)
return
}
columns, _ := rows.Columns()
count := len(columns)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for rows.Next() {
for cols := range columns {
valuePtrs[cols] = &values[cols]
}
var recid int64
// add metadata
rows.Scan(valuePtrs...)
var rid int64
for ind, col := range columns {
val := values[ind] // interface
if col == "rid" {
v, ok := val.(int64)
if ok {
recid = v
}
continue
}
if col == "sid" {
continue
}
value := fmt.Sprintf("%v", val)
for st := range searchTerms {
if strings.Contains(value, searchTerms[st]) { // issue here **************
...