go - 如何在 Golang 中对两个字符串数组进行异或?

标签 go xor

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

A = [ "ab", "cd", "ef", "gh"]
B = [ "ef", "gh"]

我想做 C = A^B

其中 C = ["ab", "cd"]

我知道 Golang 允许按字节异或,但我在文档中没有看到任何关于字符串数组的信息。

我该怎么做呢?也许有人已经为此制作了实用程序?

最佳答案

这看起来不像是 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

关于go - 如何在 Golang 中对两个字符串数组进行异或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133870/

相关文章:

inheritance - Golang 方法覆盖

java - 异或的反函数是什么?

python - 在Python中查找两个列表之间单个不同元素的索引的有效方法

python - 使用 XOR 在 Python 中查找数组中缺失的数字

c++ - 将 std::time 与随机整数混合

go - 嗨,我开始了 gogland。我跑不动

go - 如何写一个向量

linux - 通过 gopcap 发送数据包到 127.0.0.1

http - Golang negroni 和 http.NewServeMux() 问题

c++ - Qt C++ xor 用于校验和?