繁体   English   中英

如何对Golang中的两个字符串数组进行XOR?

[英]How to XOR two string arrays in Golang?

假设我有两个字符串数组。

A = [“ ab”,“ cd”,“ ef”,“ gh”]
B = [“ ef”,“ gh”]

我想做C = A ^ B

其中C = [“ ab”,“ cd”]

我知道Golang允许按字节进行XOR,但是我在文档中没有看到任何有关字符串数组的内容。

我将如何去做呢? 也许有人为此做了一个实用程序?

在Go的标准库中似乎没有这种东西,但是下面的代码可以解决这个问题:

package main

import (
    "fmt"
)

func main() {
    A := []string{"ab", "cd", "ef", "gh"}
    B := []string{"ef", "gh"}
    fmt.Println(xor(A,B))
}

func xor(list1, list2 []string) []string {
    set1 := make(map[string]bool)
    for _, s := range list1 {
        set1[s] = true
    }
    set2 := make(map[string]bool)
    for _, s := range list2 {
        set2[s] = true
    }

    var c []string
    for _, s := range list1 {
        if !set2[s] {
          c = append(c, s)
        }
    }
    for _, s := range list2 {
        if !set1[s] {
          c = append(c, s)
        }
    }
    return c
}

https://play.golang.org/p/SDPhNIQ66E

暂无
暂无

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

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