Home > Net >  How to check characters in a file and if it isn't exist Paste it with GoLang?
How to check characters in a file and if it isn't exist Paste it with GoLang?

Time:09-21

I would like to write a code with Go, that it checks if a character in the File1 exists in the File2 or not.

If it exist, skip; if it doesn't exist, write it in the file 2..

May you help me please? I couldn't paste here my code, but you can chek it from here: https://go.dev/play/p/IX_ibwya1B1

CodePudding user response:

Converting []byte to a map[byte]bool lets you use the comma ok notation to check if a byte exits in a map.

In your example, you can convert to a map the []byte of File2 and then loop for the bytes in File1 to check if some of them exist in the map.

func main() {
    file1 := []byte("Hello world!")
    file2 := []byte("Say Hello!")

    m := convertToMap(file2)

    for _, v := range file1 {
        if _, ok := m[v]; !ok {
            fmt.Println(string(v))
        }
    }
}

func convertToMap(b []byte) map[byte]bool {
    m := map[byte]bool{}
    for _, v := range b {
        m[v] = true
    }
    return m
}

https://go.dev/play/p/VktG78V324d

  • Related