英文:
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("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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论