100 lines
2.0 KiB
Go
100 lines
2.0 KiB
Go
|
package tools
|
|||
|
|
|||
|
import (
|
|||
|
"encoding/json"
|
|||
|
"reflect"
|
|||
|
"strings"
|
|||
|
)
|
|||
|
|
|||
|
// 判断某一个值是否含在切片之中
|
|||
|
func InArray(val interface{}, array interface{}) (exists bool, index int) {
|
|||
|
exists = false
|
|||
|
index = -1
|
|||
|
|
|||
|
switch reflect.TypeOf(array).Kind() {
|
|||
|
case reflect.Slice:
|
|||
|
s := reflect.ValueOf(array)
|
|||
|
|
|||
|
for i := 0; i < s.Len(); i++ {
|
|||
|
if reflect.DeepEqual(val, s.Index(i).Interface()) == true {
|
|||
|
index = i
|
|||
|
exists = true
|
|||
|
return
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
return
|
|||
|
}
|
|||
|
|
|||
|
/*
|
|||
|
分割判断
|
|||
|
s := "hello,world"
|
|||
|
substr := "world"
|
|||
|
separators := []string{",", " "}
|
|||
|
result := inArray(s, substr, separators...)
|
|||
|
fmt.Println(result) // true
|
|||
|
*/
|
|||
|
func InArrayStr(s string, substr string, contains bool, separators ...string) bool {
|
|||
|
// 使用分隔符分割字符串为切片
|
|||
|
parts := []string{s}
|
|||
|
for _, sep := range separators {
|
|||
|
newParts := make([]string, 0)
|
|||
|
for _, part := range parts {
|
|||
|
newParts = append(newParts, strings.Split(part, sep)...)
|
|||
|
}
|
|||
|
parts = newParts
|
|||
|
}
|
|||
|
|
|||
|
// 判断子字符串是否在切片中
|
|||
|
// 判断子字符串是否在切片中
|
|||
|
for _, s := range parts {
|
|||
|
if contains && strings.Contains(substr, s) {
|
|||
|
return true
|
|||
|
}
|
|||
|
if !contains && s == substr {
|
|||
|
return true
|
|||
|
}
|
|||
|
}
|
|||
|
return false
|
|||
|
}
|
|||
|
|
|||
|
/*
|
|||
|
data := map[string]interface{}{
|
|||
|
"name": "Tom",
|
|||
|
"age": 18,
|
|||
|
"gender": "male",
|
|||
|
}
|
|||
|
|
|||
|
str, err := JsonEncode(data)
|
|||
|
*/
|
|||
|
func JsonEncode(v interface{}) (string, error) {
|
|||
|
b, err := json.Marshal(v)
|
|||
|
if err != nil {
|
|||
|
return "", err
|
|||
|
}
|
|||
|
return string(b), nil
|
|||
|
}
|
|||
|
|
|||
|
/*
|
|||
|
var decodedData map[string]interface{}
|
|||
|
err = JsonDecode(str, &decodedData)
|
|||
|
*/
|
|||
|
func JsonDecode(s string, v interface{}) error {
|
|||
|
return json.Unmarshal([]byte(s), v)
|
|||
|
}
|
|||
|
|
|||
|
// 通过map主键唯一的特性过滤重复元素
|
|||
|
func RemoveDuplicateStrings(strs []string) []string {
|
|||
|
result := []string{}
|
|||
|
tempMap := map[string]byte{} // 存放不重复字符串
|
|||
|
for _, e := range strs {
|
|||
|
l := len(tempMap)
|
|||
|
tempMap[e] = 0
|
|||
|
if len(tempMap) != l { // 加入map后,map长度变化,则元素不重复
|
|||
|
result = append(result, e)
|
|||
|
}
|
|||
|
}
|
|||
|
return result
|
|||
|
}
|