I have an array of substrings and a slice of strings. I want to check if the string contains any of the substrings in the mySliceOfSubstrings slice.
mySliceOfSubstrings := []string{"hello", "world"}
mySliceOfStringsToCheck := []string{"hello mars", "hey mars"}
Is there a better way of doing it the below way of putting a loop inside a loop?
for _, string := range mySliceOfStringsToCheck {
for _, substring := range mySliceOfSubstrings {
result := strings.Contains(string, substring)
}
}
What if I wanted to check the string against two different slice of substrings?
Unless the size of data is very large and you're looking for algorithmic improvements over the O(N^2) solution you currently have, your code is fine.
For very large data you could consider using some more sophisticated data structures. For example, Go has the https://golang.org/pkg/index/suffixarray package that would let you take your slice of strings to check, preprocess it, and then perform substring lookups in logarithmic time.