dongqianzhan8325
dongqianzhan8325
2017-02-18 15:58
浏览 188
已采纳

GoLang:检查切片1中的项目是否包含在切片2中。如果包含,请删除切片2。

I have a string array: slice1 [][]string. I get the values I want using a for loop:

for _, i := range slice1 { //[string1 string2]
    fmt.Println("server: ", i[1]) //only want the second string in the array.
}

Now I have another string array: slice2 [][]string I get its values using a for loop as well:

for _, value := range output { //
    fmt.Println(value) //Prints: [ 200K, 2, "a", 22, aa-d-2, sd , MatchingString, a ]
}

I want to iterate through slice1 and check if the string2 matches "MatchingString" in Slice2. If it does, don't print the value array.

I created a for loop again to do this but its not working:

for _, value := range slice2 {
    for _, i := range slice1 {
        if strings.Contains(value[0], i[1]) {
            //skip over
        } else {
            fmt.Println(value)
        }
    }
}

Here's a sample code: https://play.golang.org/p/KMVzB2jlbG Any idea on how to do this? Thanks!

图片转代码服务由CSDN问答提供 功能建议

我有一个字符串数组:slice1 [] [] string。 我使用for循环获取所需的值:

  for _,i:= range slice1 {// [[string1 string2] 
 fmt.Println(“服务器:  “,i [1])//只想要数组中的第二个字符串。
} 
   
 
 

现在我有了另一个字符串数组:slice2 [] [] 字符串 我也使用for循环获取其值:

  for _,值:=范围输出{// 
 fmt.Println(value)//打印:  [200K,2,“ a”,22,aa-d-2,sd,MatchingString,a] 
} 
   
 
 

我想遍历slice1和 检查string2是否与Slice2中的“ MatchingString”匹配。 如果是这样,请勿打印值数组。

我再次创建了一个for循环来执行此操作,但它不起作用:

  for _,值:= range slice2 {
 对于_,i:=范围slice1 {
如果是字符串。包含(value [0],i [1]){
 //跳过
}否则{
 fmt.Println(value)
} \  n} 
} 
   
 
 

下面是示例代码: https://play.golang.org/p/KMVzB2jlbG 关于如何执行此操作的任何想法? 谢谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douao1959
    douao1959 2017-02-18 17:20
    已采纳

    If I'm reading your question correctly, you are trying to print all those subslices of slice2 that have the property that none of the strings within are the second element of a slice in slice1. If so, you can obtain that through

    Slice2Loop:
        for _, value := range slice2 {
            for _, slice2string := range value {
                for _, i := range slice1 {
                    if slice2string == i[1] {
                        continue Slice2Loop
                    }
                }
            }
            fmt.Println(value)
        }
    
    点赞 评论

相关推荐