1

Suppose I have a slice of strings like:

fruits := {"apple", "orange", "banana"}

and a map like

box:= map[string]int{
    "chicken": 1,
    "drinks": 4,
    "apples": 42,
}

What is the most efficient way to check whether the box contains any apple, orange or banana? Notice that here we seek not exact match but a key that CONTAINS certain strings. So simple key search does not work here.

I know I can extract keys from the map:

keys := make([]string)
for k := range box {
    keys = append(keys, k)
}

And then iterate over both slices to search among the keys:

for _, f := range fruits {
  for _, k in keys {
      if strings.Contains(k, f) {
       fmt.Println("Fruit found!")
       }
   }

But that refutes the advantage of using map instead of slice for string searchs. So is there better way to do so?

1 Answer 1

5

You don't need to extract the keys:

for _, f := range fruits {
  for k,fruit := range box {
      if strings.Contains(k, f) {
       fmt.Printf("Fruit found!: %s",fruit)
       }
   }
}

If you only need to check if key exists, you can write for k := range box

Since this is a contains search, there is no easy way to do it. If it was a begins with search, there are other data structures you might want to look at, such as a trie, or prefix-tree. There isn't standard library support for those.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.