123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- package stringx
- import (
- "errors"
- "github.com/tal-tech/go-zero/core/lang"
- )
- var (
- ErrInvalidStartPosition = errors.New("start position is invalid")
- ErrInvalidStopPosition = errors.New("stop position is invalid")
- )
- func Contains(list []string, str string) bool {
- for _, each := range list {
- if each == str {
- return true
- }
- }
- return false
- }
- func Filter(s string, filter func(r rune) bool) string {
- var n int
- chars := []rune(s)
- for i, x := range chars {
- if n < i {
- chars[n] = x
- }
- if !filter(x) {
- n++
- }
- }
- return string(chars[:n])
- }
- func HasEmpty(args ...string) bool {
- for _, arg := range args {
- if len(arg) == 0 {
- return true
- }
- }
- return false
- }
- func NotEmpty(args ...string) bool {
- return !HasEmpty(args...)
- }
- func Remove(strings []string, strs ...string) []string {
- out := append([]string(nil), strings...)
- for _, str := range strs {
- var n int
- for _, v := range out {
- if v != str {
- out[n] = v
- n++
- }
- }
- out = out[:n]
- }
- return out
- }
- func Reverse(s string) string {
- runes := []rune(s)
- for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
- runes[from], runes[to] = runes[to], runes[from]
- }
- return string(runes)
- }
- // Substr returns runes between start and stop [start, stop) regardless of the chars are ascii or utf8
- func Substr(str string, start int, stop int) (string, error) {
- rs := []rune(str)
- length := len(rs)
- if start < 0 || start > length {
- return "", ErrInvalidStartPosition
- }
- if stop < 0 || stop > length {
- return "", ErrInvalidStopPosition
- }
- return string(rs[start:stop]), nil
- }
- func TakeOne(valid, or string) string {
- if len(valid) > 0 {
- return valid
- }
- return or
- }
- func TakeWithPriority(fns ...func() string) string {
- for _, fn := range fns {
- val := fn()
- if len(val) > 0 {
- return val
- }
- }
- return ""
- }
- func Union(first, second []string) []string {
- set := make(map[string]lang.PlaceholderType)
- for _, each := range first {
- set[each] = lang.Placeholder
- }
- for _, each := range second {
- set[each] = lang.Placeholder
- }
- merged := make([]string, 0, len(set))
- for k := range set {
- merged = append(merged, k)
- }
- return merged
- }
|