Home > Article > Backend Development > 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!
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) }
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)) }
BTW, do you really need to do this on []rune
s? 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!