字符串切片去重

字符串切片去重

使用sort.String 方法对切片进行排序
使用发射机制 对切片进行排序
去重前的排序很重要

package main

import (
    "fmt"
    "reflect"
    "sort"
)

func main() {
    b := []string{"12", "a", "b", "c", "a", "12"}
    fmt.Println("去重前 ==>", b)
    // 输出结果 [12 a b c a 12]
    fmt.Println("去重后 ==>", Duplicate(b))
    // 输出结果 [12 a b c]

    // 如果是int 那么使用 sort.Ints方法
    //c := []int{1, 1, 2, 4, 6, 7, 8, 4, 3, 2, 5, 6, 6, 8}
    //sort.Ints(c)
    //fmt.Println(DeleteDuplicateValue(c))
}
func Duplicate(a []string) (ret []interface{}) {
    sort.Strings(a)
    va := reflect.ValueOf(a)
    for i := 0; i < va.Len(); i++ {
        if i > 0 && reflect.DeepEqual(va.Index(i-1).Interface(), va.Index(i).Interface()) {
            continue
        }
        ret = append(ret, va.Index(i).Interface())
    }
    return ret
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!