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

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!

  • 写回答

1条回答 默认 最新

  • 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)
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?