Home > Backend Development > Golang > Remove same elements from two arrays Golang

Remove same elements from two arrays Golang

WBOY
Release: 2024-02-11 22:54:08
forward
794 people have browsed it

Remove same elements from two arrays Golang

php editor Apple brings you an article about deleting identical elements from two arrays. In programming, we often encounter situations where we need to delete the same elements in an array. This operation can help us process data better. This article will introduce how to use Golang language to delete the same elements from two arrays. I hope it will be helpful to your programming work. Let’s take a look!

Question content

a:=[]rune("/storage/emulated/0/Custom_Scripts/Golang/")

b:=[]rune("/storage/emulated/0/")

There are two slices a && b, in the loop we should take each element from the second slice $b and compare it with the elements in the first slice $a, if they are the same, then we Will start from the first slice $a The solution should be without any package except fmt (only for printing the final array) and by two ways: Use looping fists Second map

Trying to release it this way but I'm getting an out of range panic, can anyone help me?

package main
import(
"fmt"
)
func main() {
    fileMeta := 
[]rune("/storage/emulated/0/Custom_Scripts/Golang/")
    delChr := []rune("/storage/emulated/0")
    for i, j := range fileMeta {
        for _, m := range delChr {
            if m == j {
               //fileMeta[i] = ""
               fileMeta = append(fileMeta[:i], 
fileMeta[i+1:]...)
            }
        }
    }
    fmt.Println(fileMeta)
  }
Copy after login

Solution

I won’t reinvent the wheel:

package main

import (
    "fmt"
    "strings"
)

func main() {
    fileMeta := []rune("/storage/emulated/0/Custom_Scripts/Golang/")
    delChr := []rune("/storage/emulated/0")

    fm := string(fileMeta)
    pfx := string(delChr)

    if tail := strings.TrimPrefix(fm, pfx); len(tail) != len(fm) {
        fileMeta = []rune(tail)
    }

    fmt.Println(fileMeta, string(fileMeta))
}
Copy after login

BTW, do you really need to do this on []runes? This is unnatural for most applications - why not just use the correct string right away?

The above is the detailed content of Remove same elements from two arrays Golang. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template