如何在文件中检查字符,并在不存在时使用GoLang粘贴它?

huangapple go评论90阅读模式
英文:

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

问题

我想用Go语言编写一段代码,它可以检查File1中的字符是否存在于File2中。

如果存在,则跳过;如果不存在,则将其写入File2。

你能帮我吗?我无法在这里粘贴我的代码,但你可以从这里查看它:
https://go.dev/play/p/IX_ibwya1B1

英文:

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:
<a href="https://go.dev/play/p/IX_ibwya1B1">https://go.dev/play/p/IX_ibwya1B1</a>

答案1

得分: 0

[]byte转换为map[byte]bool可以使用逗号-OK符号来检查字节是否存在于映射中。

在你的示例中,你可以将File2的[]byte转换为映射,然后循环遍历File1中的字节,检查它们是否存在于映射中。

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

英文:

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(&quot;Hello world!&quot;)
	file2 := []byte(&quot;Say Hello!&quot;)

	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

huangapple
  • 本文由 发表于 2022年9月14日 02:12:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/73707548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定