strutil

package
v0.5.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2022 License: MIT Imports: 21 Imported by: 125

README

String Util

This is a go string operate util package.

Install

go get github.com/gookit/goutil/dump

Usage

ss := strutil.ToArray("a,b,c", ",")
// Output: []string{"a", "b", "c"}

ints, err := strutil.ToIntSlice("1,2,3")
// Output: []int{1, 2, 3}

Functions

func B64Encode(str string) string
func Bool(s string) (bool, error)
func Camel(s string, sep ...string) string
func CamelCase(s string, sep ...string) string
func FilterEmail(s string) string
func GenMd5(src interface{}) string
func LowerFirst(s string) string
func Lowercase(s string) string
func Md5(src interface{}) string
func MustBool(s string) bool
func MustString(in interface{}) string
func PadLeft(s, pad string, length int) string
func PadRight(s, pad string, length int) string
func Padding(s, pad string, length int, pos uint8) string
func PrettyJSON(v interface{}) (string, error)
func RandomBytes(length int) ([]byte, error)
func RandomString(length int) (string, error)
func RenderTemplate(input string, data interface{}, fns template.FuncMap, isFile ...bool) string
func Repeat(s string, times int) string
func RepeatRune(char rune, times int) (chars []rune)
func Replaces(str string, pairs map[string]string) string
func Similarity(s, t string, rate float32) (float32, bool)
func Snake(s string, sep ...string) string
func SnakeCase(s string, sep ...string) string
func Split(s, sep string) (ss []string)
func String(val interface{}) (string, error)
func Substr(s string, pos, length int) string
func ToArray(s string, sep ...string) []string
func ToBool(s string) (bool, error)
func ToIntSlice(s string, sep ...string) (ints []int, err error)
func ToInts(s string, sep ...string) ([]int, error)
func ToSlice(s string, sep ...string) []string
func ToString(val interface{}) (str string, err error)
func ToTime(s string, layouts ...string) (t time.Time, err error)
func Trim(s string, cutSet ...string) string
func TrimLeft(s string, cutSet ...string) string
func TrimRight(s string, cutSet ...string) string
func URLDecode(s string) string
func URLEncode(s string) string
func UpperFirst(s string) string
func UpperWord(s string) string
func Uppercase(s string) string

Documentation

Overview

Package strutil provide some string,char,byte util functions

Index

Constants

View Source
const (
	Numbers   = "0123456789"
	AlphaBet  = "abcdefghijklmnopqrstuvwxyz"
	AlphaBet1 = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
	AlphaNum  = "abcdefghijklmnopqrstuvwxyz0123456789"
	AlphaNum2 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	AlphaNum3 = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
)

some consts string chars

View Source
const (
	PosLeft uint8 = iota
	PosRight
)

Position for padding string

Variables

View Source
var (
	ErrConvertFail  = errors.New("convert data type is failure")
	ErrInvalidParam = errors.New("invalid input parameter")
)
View Source
var (
	DefMinInt = 1000
	DefMaxInt = 9999
)

global id:

https://github.com/rs/xid
https://github.com/satori/go.uuid

Equal check

View Source
var (
	Title = strings.ToTitle
)

Title Some alias methods.

Functions

func AddSlashes added in v0.5.6

func AddSlashes(s string) string

AddSlashes add slashes for the string.

func AnyToString added in v0.3.10

func AnyToString(val interface{}, defaultAsErr bool) (str string, err error)

AnyToString convert value to string.

if defaultAsErr is False, will use fmt.Sprint convert complex type

func B32Decode added in v0.5.3

func B32Decode(str string) string

B32Decode base32 decode

func B32Encode added in v0.5.3

func B32Encode(str string) string

B32Encode base32 encode

func B64Decode added in v0.5.3

func B64Decode(str string) string

B64Decode base64 decode

func B64Encode added in v0.2.2

func B64Encode(str string) string

B64Encode base64 encode

func Base64 added in v0.2.3

func Base64(str string) string

Base64 encode

func Bool added in v0.2.2

func Bool(s string) (bool, error)

Bool parse string to bool

func Byte2str added in v0.3.14

func Byte2str(b []byte) string

Byte2str convert bytes to string

func Byte2string added in v0.3.14

func Byte2string(b []byte) string

Byte2string convert bytes to string

func BytePos added in v0.3.12

func BytePos(s string, bt byte) int

BytePos alias of the strings.IndexByte

func Camel added in v0.2.2

func Camel(s string, sep ...string) string

Camel alias of the CamelCase

func CamelCase added in v0.2.2

func CamelCase(s string, sep ...string) string

CamelCase convert string to camel case.

Support:

"range_price" -> "rangePrice"
"range price" -> "rangePrice"
"range-price" -> "rangePrice"

func Cut added in v0.5.0

func Cut(s, sep string) (before string, after string, found bool)

Cut same of the strings.Cut

func EscapeHTML added in v0.2.2

func EscapeHTML(s string) string

EscapeHTML escape html string

func EscapeJS added in v0.2.2

func EscapeJS(s string) string

EscapeJS escape javascript string

func FilterEmail added in v0.2.2

func FilterEmail(s string) string

FilterEmail filter email, clear invalid chars.

func GenMd5

func GenMd5(src interface{}) string

GenMd5 Generate a 32-bit md5 string

func HasAllSubs added in v0.4.0

func HasAllSubs(s string, subs []string) bool

HasAllSubs all substr in the given string.

func HasOnePrefix added in v0.4.0

func HasOnePrefix(s string, prefixes []string) bool

HasOnePrefix the string start withs one of the subs

func HasOneSub added in v0.4.0

func HasOneSub(s string, subs []string) bool

HasOneSub substr in the given string.

func HasPrefix added in v0.3.12

func HasPrefix(s string, prefix string) bool

HasPrefix substr in the given string.

func HasSuffix added in v0.3.12

func HasSuffix(s string, suffix string) bool

HasSuffix substr in the given string.

func Implode added in v0.5.0

func Implode(sep string, ss ...string) string

Implode alias of strings.Join

func Int added in v0.2.8

func Int(s string) (int, error)

Int convert string to int, alias of ToInt()

func Int64 added in v0.5.5

func Int64(s string) int64

Int64 convert string to int, will ignore error

func Int64OrErr added in v0.5.5

func Int64OrErr(s string) (int64, error)

Int64OrErr convert string to int

func Int64OrPanic added in v0.5.5

func Int64OrPanic(s string) int64

Int64OrPanic convert value to int, will panic on error

func IntOrPanic added in v0.4.1

func IntOrPanic(s string) int

IntOrPanic convert value to int, will panic on error

func Ints added in v0.3.13

func Ints(s string, sep ...string) []int

Ints alias of the ToIntSlice()

func IsAlphaNum added in v0.3.11

func IsAlphaNum(c uint8) bool

IsAlphaNum reports whether the byte is an ASCII letter, number, or underscore

func IsAlphabet added in v0.2.13

func IsAlphabet(char uint8) bool

IsAlphabet char

func IsBlank added in v0.3.12

func IsBlank(s string) bool

IsBlank returns true if the given string is all space characters.

func IsBlankBytes added in v0.3.12

func IsBlankBytes(bs []byte) bool

IsBlankBytes returns true if the given []byte is all space characters.

func IsEmpty added in v0.4.1

func IsEmpty(s string) bool

IsEmpty returns true if the given string is empty.

func IsEndOf added in v0.3.12

func IsEndOf(s, suffix string) bool

IsEndOf alias of the strings.HasSuffix

func IsNotBlank added in v0.4.1

func IsNotBlank(s string) bool

IsNotBlank returns true if the given string is not blank.

func IsNumeric added in v0.3.12

func IsNumeric(c byte) bool

IsNumeric returns true if the given character is a numeric, otherwise false.

func IsSpace added in v0.3.12

func IsSpace(c byte) bool

IsSpace returns true if the given character is a space, otherwise false.

func IsSpaceRune added in v0.3.12

func IsSpaceRune(r rune) bool

IsSpaceRune returns true if the given rune is a space, otherwise false.

func IsStartOf added in v0.3.12

func IsStartOf(s, prefix string) bool

IsStartOf alias of the strings.HasPrefix

func IsStartsOf added in v0.4.0

func IsStartsOf(s string, prefixes []string) bool

IsStartsOf alias of the HasOnePrefix

func IsSymbol added in v0.3.12

func IsSymbol(r rune) bool

IsSymbol reports whether the rune is a symbolic character.

func IsValidUtf8 added in v0.5.6

func IsValidUtf8(s string) bool

IsValidUtf8 valid utf8 string check

func Join added in v0.5.0

func Join(sep string, ss ...string) string

Join alias of strings.Join

func JoinSubs added in v0.5.3

func JoinSubs(sep string, ss []string) string

JoinSubs alias of strings.Join

func LTrim added in v0.5.0

func LTrim(s string, cutSet ...string) string

LTrim alias of TrimLeft

func Len added in v0.3.12

func Len(s string) int

Len of the string

func Lower added in v0.2.2

func Lower(s string) string

Lower alias of the strings.ToLower()

func LowerFirst

func LowerFirst(s string) string

LowerFirst lower first char

func Lowercase added in v0.2.2

func Lowercase(s string) string

Lowercase alias of the strings.ToLower()

func Ltrim added in v0.3.12

func Ltrim(s string, cutSet ...string) string

Ltrim alias of TrimLeft

func MD5 added in v0.5.6

func MD5(src interface{}) string

MD5 Generate a 32-bit md5 string

func Md5 added in v0.2.2

func Md5(src interface{}) string

Md5 Generate a 32-bit md5 string

func MicroTimeHexID added in v0.3.6

func MicroTimeHexID() string

MicroTimeHexID generate. return like: 5b5f0588af1761ad3(len: 16-17)

func MicroTimeID added in v0.3.6

func MicroTimeID() string

MicroTimeID generate. return like: 16074145697981929446(len: 20)

func MustBool added in v0.2.2

func MustBool(s string) bool

MustBool convert, will panic on error

func MustCut added in v0.5.0

func MustCut(s, sep string) (before string, after string)

MustCut always returns two substring.

func MustInt added in v0.2.8

func MustInt(s string) int

MustInt convert string to int, will panic on error

func MustString added in v0.2.2

func MustString(in interface{}) string

MustString convert value to string, TODO will panic on error

func MustToTime added in v0.5.1

func MustToTime(s string, layouts ...string) time.Time

MustToTime convert date string to time.Time

func PadLeft

func PadLeft(s, pad string, length int) string

PadLeft a string.

func PadRight

func PadRight(s, pad string, length int) string

PadRight a string.

func Padding

func Padding(s, pad string, length int, pos uint8) string

Padding a string.

func PrettyJSON

func PrettyJSON(v interface{}) (string, error)

PrettyJSON get pretty Json string Deprecated: please use fmtutil.PrettyJSON() or jsonutil.Pretty() instead it

func QuietBool added in v0.5.3

func QuietBool(s string) bool

QuietBool convert to bool, will ignore error

func QuietInt added in v0.5.5

func QuietInt(s string) int

QuietInt convert string to int, will ignore error

func QuietInt64 added in v0.5.5

func QuietInt64(s string) int64

QuietInt64 convert string to int, will ignore error

func QuietString added in v0.5.3

func QuietString(in interface{}) string

QuietString convert value to string, will ignore error

func RTrim added in v0.5.0

func RTrim(s string, cutSet ...string) string

RTrim alias of TrimRight

func RandomBytes

func RandomBytes(length int) ([]byte, error)

RandomBytes generate

func RandomChars added in v0.3.6

func RandomChars(ln int) string

RandomChars generate give length random chars at `a-z`

func RandomCharsV2 added in v0.3.6

func RandomCharsV2(ln int) string

RandomCharsV2 generate give length random chars in `0-9a-z`

func RandomCharsV3 added in v0.3.6

func RandomCharsV3(ln int) string

RandomCharsV3 generate give length random chars in `0-9a-zA-Z`

func RandomString

func RandomString(length int) (string, error)

RandomString generate. Example:

	// this will give us a 44 byte, base64 encoded output
	token, err := RandomString(32)
	if err != nil {
    // Serve an appropriately vague error to the
    // user, but log the details internally.
	}

func RenderTemplate

func RenderTemplate(input string, data interface{}, fns template.FuncMap, isFile ...bool) string

RenderTemplate render text template

func RenderText added in v0.2.4

func RenderText(input string, data interface{}, fns template.FuncMap, isFile ...bool) string

RenderText render text template

func Repeat

func Repeat(s string, times int) string

Repeat a string

func RepeatBytes added in v0.3.10

func RepeatBytes(char byte, times int) (chars []byte)

RepeatBytes repeat a byte char.

func RepeatRune

func RepeatRune(char rune, times int) (chars []rune)

RepeatRune repeat a rune char.

func Replaces

func Replaces(str string, pairs map[string]string) string

Replaces replace multi strings

pairs: {old1: new1, old2: new2, ...}

Can also use:

strings.NewReplacer("old1", "new1", "old2", "new2").Replace(str)

func Rtrim added in v0.3.12

func Rtrim(s string, cutSet ...string) string

Rtrim alias of TrimRight

func RuneLen added in v0.5.6

func RuneLen(s string) int

RuneLen of the string

func RunePos added in v0.3.12

func RunePos(s string, ru rune) int

RunePos alias of the strings.IndexRune

func Similarity

func Similarity(s, t string, rate float32) (float32, bool)

Similarity calc for two string. Usage:

rate, ok := Similarity("hello", "he")

func Snake added in v0.2.2

func Snake(s string, sep ...string) string

Snake alias of the SnakeCase

func SnakeCase added in v0.2.2

func SnakeCase(s string, sep ...string) string

SnakeCase convert. eg "RangePrice" -> "range_price"

func Split

func Split(s, sep string) (ss []string)

Split string to slice. will trim each item and filter empty string node.

func SplitN added in v0.4.0

func SplitN(s, sep string, n int) (ss []string)

SplitN string to slice. will filter empty string node.

func SplitNTrimmed added in v0.4.0

func SplitNTrimmed(s, sep string, n int) (ss []string)

SplitNTrimmed split string to slice. will trim space for each node, but not filter empty

func SplitNValid added in v0.4.0

func SplitNValid(s, sep string, n int) (ss []string)

SplitNValid string to slice. will filter empty string node.

func SplitTrimmed added in v0.4.0

func SplitTrimmed(s, sep string) (ss []string)

SplitTrimmed split string to slice. will trim space for each node, but not filter empty

func SplitValid added in v0.4.0

func SplitValid(s, sep string) (ss []string)

SplitValid string to slice. will trim each item and filter empty string node.

func StrPos added in v0.3.12

func StrPos(s, sub string) int

StrPos alias of the strings.Index

func String added in v0.2.2

func String(val interface{}) (string, error)

String convert val to string

func StringOrErr added in v0.5.3

func StringOrErr(val interface{}) (string, error)

StringOrErr convert value to string, return error on failed

func Strings added in v0.3.13

func Strings(s string, sep ...string) []string

Strings alias of the ToSlice()

func StripSlashes added in v0.5.6

func StripSlashes(s string) string

StripSlashes strip slashes for the string.

func Substr

func Substr(s string, pos, length int) string

Substr for a string. if length <= 0, return pos to end.

func ToArray added in v0.2.2

func ToArray(s string, sep ...string) []string

ToArray alias of the ToSlice()

func ToBool added in v0.2.2

func ToBool(s string) (bool, error)

ToBool convert string to bool

func ToBytes added in v0.3.14

func ToBytes(s string) (b []byte)

ToBytes convert string to bytes

func ToDuration added in v0.5.6

func ToDuration(s string) (time.Duration, error)

ToDuration parses a duration string. such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

func ToInt added in v0.2.8

func ToInt(s string) (int, error)

ToInt convert string to int

func ToIntSlice added in v0.2.2

func ToIntSlice(s string, sep ...string) (ints []int, err error)

ToIntSlice split string to slice and convert item to int.

func ToInts added in v0.2.2

func ToInts(s string, sep ...string) ([]int, error)

ToInts alias of the ToIntSlice()

func ToSlice added in v0.2.2

func ToSlice(s string, sep ...string) []string

ToSlice split string to array.

func ToString added in v0.2.2

func ToString(val interface{}) (string, error)

ToString convert value to string

func ToStrings added in v0.3.13

func ToStrings(s string, sep ...string) []string

ToStrings alias of the ToSlice()

func ToTime added in v0.2.2

func ToTime(s string, layouts ...string) (t time.Time, err error)

ToTime convert date string to time.Time

func Trim added in v0.2.2

func Trim(s string, cutSet ...string) string

Trim string. if cutSet is empty, will trim SPACE.

func TrimLeft added in v0.2.2

func TrimLeft(s string, cutSet ...string) string

TrimLeft char in the string. if cutSet is empty, will trim SPACE.

func TrimRight added in v0.2.2

func TrimRight(s string, cutSet ...string) string

TrimRight char in the string. if cutSet is empty, will trim SPACE.

func URLDecode added in v0.2.2

func URLDecode(s string) string

URLDecode decode url string.

func URLEncode added in v0.2.2

func URLEncode(s string) string

URLEncode encode url string.

func Upper added in v0.2.2

func Upper(s string) string

Upper alias of the strings.ToUpper()

func UpperFirst

func UpperFirst(s string) string

UpperFirst upper first char

func UpperWord

func UpperWord(s string) string

UpperWord Change the first character of each word to uppercase

func Uppercase added in v0.2.2

func Uppercase(s string) string

Uppercase alias of the strings.ToUpper()

func Utf8Len added in v0.5.6

func Utf8Len(s string) int

Utf8Len of the string

func Utf8len added in v0.3.12

func Utf8len(s string) int

Utf8len of the string

func VersionCompare added in v0.5.5

func VersionCompare(v1, v2, op string) bool

VersionCompare for two version string.

Types

type BaseEncoder added in v0.5.3

type BaseEncoder struct {
	// Base value
	Base int
}

BaseEncoder struct

func NewBaseEncoder added in v0.5.3

func NewBaseEncoder(base int) *BaseEncoder

NewBaseEncoder instance

func (*BaseEncoder) Decode added in v0.5.3

func (be *BaseEncoder) Decode(s string) (string, error)

Decode handle

func (*BaseEncoder) Encode added in v0.5.3

func (be *BaseEncoder) Encode(s string) string

Encode handle

type Buffer added in v0.5.3

type Buffer struct {
	bytes.Buffer
}

Buffer wrap and extends the bytes.Buffer

func NewEmptyBuffer added in v0.5.3

func NewEmptyBuffer() *Buffer

NewEmptyBuffer instance

func (*Buffer) MustWriteString added in v0.5.3

func (b *Buffer) MustWriteString(ss ...string)

MustWriteString to buffer

func (*Buffer) QuietWriteByte added in v0.5.5

func (b *Buffer) QuietWriteByte(c byte)

QuietWriteByte to buffer

func (*Buffer) QuietWriteString added in v0.5.3

func (b *Buffer) QuietWriteString(ss ...string)

QuietWriteString to buffer

func (*Buffer) QuietWritef added in v0.5.3

func (b *Buffer) QuietWritef(tpl string, vs ...interface{})

QuietWritef write message to buffer

func (*Buffer) QuietWriteln added in v0.5.3

func (b *Buffer) QuietWriteln(ss ...string)

QuietWriteln write message to buffer with newline

type ByteChanPool added in v0.4.0

type ByteChanPool struct {
	// contains filtered or unexported fields
}

ByteChanPool struct

Usage:

bp := strutil.NewByteChanPool(500, 1024, 1024)
buf:=bp.Get()
defer bp.Put(buf)
// use buf do something ...

refer https://www.flysnow.org/2020/08/21/golang-chan-byte-pool.html from https://github.com/minio/minio/blob/master/internal/bpool/bpool.go

func NewByteChanPool added in v0.4.0

func NewByteChanPool(maxSize int, width int, capWidth int) *ByteChanPool

NewByteChanPool instance

func (*ByteChanPool) Get added in v0.4.0

func (bp *ByteChanPool) Get() (b []byte)

Get gets a []byte from the BytePool, or creates a new one if none are available in the pool.

func (*ByteChanPool) Put added in v0.4.0

func (bp *ByteChanPool) Put(b []byte)

Put returns the given Buffer to the BytePool.

func (*ByteChanPool) Width added in v0.4.0

func (bp *ByteChanPool) Width() (n int)

Width returns the width of the byte arrays in this pool.

func (*ByteChanPool) WidthCap added in v0.4.0

func (bp *ByteChanPool) WidthCap() (n int)

WidthCap returns the cap width of the byte arrays in this pool.

type SimilarComparator

type SimilarComparator struct {
	// contains filtered or unexported fields
}

SimilarComparator definition links:

https://github.com/mkideal/cli/blob/master/fuzzy.go

func NewComparator

func NewComparator(src, dst string) *SimilarComparator

NewComparator create

func (*SimilarComparator) Similar

func (c *SimilarComparator) Similar(minDifferRate float32) (float32, bool)

Similar by minDifferRate Usage:

c := NewComparator("hello", "he")
rate, ok :c.Similar(0.3)

type StrVal added in v0.5.3

type StrVal = Value

StrVal string. alias of Value

type Value added in v0.5.5

type Value string

Value string

func (Value) Bool added in v0.5.5

func (s Value) Bool() bool

Bool convert

func (Value) Bytes added in v0.5.5

func (s Value) Bytes() []byte

Bytes string to bytes

func (Value) HasPrefix added in v0.5.5

func (s Value) HasPrefix(sub string) bool

HasPrefix prefix

func (Value) HasSuffix added in v0.5.5

func (s Value) HasSuffix(sub string) bool

HasSuffix suffix

func (Value) Int added in v0.5.5

func (s Value) Int() int

Int convert

func (Value) Int64 added in v0.5.5

func (s Value) Int64() int64

Int64 convert

func (Value) IsEmpty added in v0.5.5

func (s Value) IsEmpty() bool

IsEmpty check

func (Value) IsEndWith added in v0.5.5

func (s Value) IsEndWith(sub string) bool

IsEndWith suffix

func (Value) IsStartWith added in v0.5.5

func (s Value) IsStartWith(sub string) bool

IsStartWith prefix

func (*Value) Set added in v0.5.5

func (s *Value) Set(val string) error

Set value

func (Value) Split added in v0.5.5

func (s Value) Split(sep string) []string

Split string

func (Value) SplitN added in v0.5.5

func (s Value) SplitN(sep string, n int) []string

SplitN string

func (Value) String added in v0.5.5

func (s Value) String() string

Value string

func (Value) TrimSpace added in v0.5.5

func (s Value) TrimSpace() Value

TrimSpace string and return new

func (Value) Val added in v0.5.5

func (s Value) Val() string

Val string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL