简体   繁体   English

如何查看映射键是否包含某些字符串?

[英]How to see if map keys contain certain strings?

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 ?检查box中是否装有appleorangebanana的最有效方法是什么? 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.但这否定了使用 map 而不是 slice 进行字符串搜索的优势。 So is there better way to do so?那么有没有更好的方法呢?

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如果只需要检查key是否存在,可以写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.没有标准库支持这些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM