简体   繁体   中英

How to XOR two string arrays in Golang?

Let's say I have two string array.

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

I want to do C = A^B

where C = ["ab", "cd"]

I'm aware Golang allows XOR byte-wise, but I haven't seen anything for string arrays in the documentation.

How would I go about doing this? Perhaps there is a utility someone has already made for this?

This doesn't seem like something that would go in a standard library in Go, but here's a bit of code that does the trick:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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