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

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

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中的字节,检查它们是否存在于映射中。

  1. func main() {
  2. file1 := []byte("Hello world!")
  3. file2 := []byte("Say Hello!")
  4. m := convertToMap(file2)
  5. for _, v := range file1 {
  6. if _, ok := m[v]; !ok {
  7. fmt.Println(string(v))
  8. }
  9. }
  10. }
  11. func convertToMap(b []byte) map[byte]bool {
  12. m := map[byte]bool{}
  13. for _, v := range b {
  14. m[v] = true
  15. }
  16. return m
  17. }

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.

  1. func main() {
  2. file1 := []byte(&quot;Hello world!&quot;)
  3. file2 := []byte(&quot;Say Hello!&quot;)
  4. m := convertToMap(file2)
  5. for _, v := range file1 {
  6. if _, ok := m[v]; !ok {
  7. fmt.Println(string(v))
  8. }
  9. }
  10. }
  11. func convertToMap(b []byte) map[byte]bool {
  12. m := map[byte]bool{}
  13. for _, v := range b {
  14. m[v] = true
  15. }
  16. return m
  17. }

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:

确定