strings2

package
v7.7.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2021 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package strings2 is the supplement of the standard library of `strings`.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultFormat = NewFormat("{", "}")

DefaultFormat is the default global formatter.

Functions

func FmtString

func FmtString(s string, kwargs ...interface{}) string

FmtString formats the string s by DefaultFormat, which is short for

DefaultFormat.Format(s, kwargs...)
Example
s1 := FmtString("hello {name}. {name}.", "name", "world")
fmt.Println(s1)

s2 := FmtString("hello {name}. {name}.", "name", "world", "age", 123)
fmt.Println(s2)

s3 := FmtString("hello {name}. {name}.", "age", 123)
fmt.Println(s3)

s4 := FmtString("hello {name}. You are [{age:6d}].", "name", "world", "age", 123)
fmt.Println(s4)
Output:

hello world. world.
hello world. world.
hello {name}. {name}.
hello world. You are [   123].

func FmtStringByFunc

func FmtStringByFunc(s string, getValue func(string) (interface{}, bool)) string

FmtStringByFunc formats the string s by DefaultFormat, which is short for

DefaultFormat.FormatByFunc(s, getValue)
Example
getValue := func(key string) (interface{}, bool) {
	switch key {
	case "name":
		return "world", true
	case "age":
		return 123, true
	default:
		return nil, false
	}
}

s1 := FmtStringByFunc("hello {name}. {name}.", getValue)
fmt.Println(s1)

s2 := FmtStringByFunc("hello {name}. {name}.", getValue)
fmt.Println(s2)

s3 := FmtStringByFunc("hello {name}. {name1}.", getValue)
fmt.Println(s3)

s4 := FmtStringByFunc("hello {name}. You are [{age:6d}].", getValue)
fmt.Println(s4)
Output:

hello world. world.
hello world. world.
hello world. {name1}.
hello world. You are [   123].

func FmtStringByMap

func FmtStringByMap(s string, kwargs map[string]interface{}) string

FmtStringByMap formats the string s by DefaultFormat, which is short for

DefaultFormat.FormatByMap(s, kwargs)
Example
s1 := FmtStringByMap("hello {name}. {name}.", map[string]interface{}{"name": "world"})
fmt.Println(s1)

s2 := FmtStringByMap("hello {name}. {name}.", map[string]interface{}{"name": "world", "age": 123})
fmt.Println(s2)

s3 := FmtStringByMap("hello {name}. {name}.", map[string]interface{}{"age": 123})
fmt.Println(s3)

s4 := FmtStringByMap("hello {name}. You are [{age:6d}].", map[string]interface{}{"name": "world", "age": 123})
fmt.Println(s4)
Output:

hello world. world.
hello world. world.
hello {name}. {name}.
hello world. You are [   123].

func FmtStringOutput

func FmtStringOutput(w io.Writer, s string, getValue func(string) (interface{}, bool)) (int, error)

FmtStringOutput formats the string s by DefaultFormat, which is short for

DefaultFormat.FormatOutput(w, s, getValue)

func SafeWriteString

func SafeWriteString(w io.Writer, s string, escape, quote bool) (n int, err error)

SafeWriteString writes s into w.

If escape is true, it will convert '"' to '\"'.

if quote is true, it will output a '"' on both sides of s.

Example
buf := bytes.NewBuffer(nil)

SafeWriteString(buf, `abcefg`, true, true)
buf.WriteByte('\n')

SafeWriteString(buf, `abcefg`, true, false)
buf.WriteByte('\n')

SafeWriteString(buf, `abcefg`, false, true)
buf.WriteByte('\n')

SafeWriteString(buf, `abcefg`, false, false)
buf.WriteByte('\n')

SafeWriteString(buf, `abc"efg`, true, true)
buf.WriteByte('\n')

SafeWriteString(buf, `abc"efg`, true, false)
buf.WriteByte('\n')

SafeWriteString(buf, `abc"efg`, false, true)
buf.WriteByte('\n')

SafeWriteString(buf, `abc"efg`, false, false)
buf.WriteByte('\n')

fmt.Print(buf.String())
Output:

"abcefg"
abcefg
"abcefg"
abcefg
"abc\"efg"
abc\"efg
"abc"efg"
abc"efg

func Split

func Split(s string, filter func(c rune) bool) []string

Split splits the string of s by the filter. Split will pass each rune to the filter to determine whether it is the separator.

Example
s := "   1   2   3   "
ss := Split(s, unicode.IsSpace)
fmt.Printf("[len=%v: %v-%v-%v]\n", len(ss), ss[0], ss[1], ss[2])
Output:

[len=3: 1-2-3]

func SplitN

func SplitN(s string, filter func(c rune) bool, maxsplit int) []string

SplitN splits the string of s by the filter. Split will pass each rune to the filter to determine whether it is the separator, but only maxsplit times.

If maxsplit is equal to 0, don't split; greater than 0, only split maxsplit times; less than 0, don't limit. If the leading rune is the separator, it doesn't consume the split maxsplit.

Notice: The result does not have the element of nil.

Example
s := "   1   2   3   "

s1 := SplitN(s, unicode.IsSpace, -1)
fmt.Printf("[len=%v: -%v-%v-%v-]\n", len(s1), s1[0], s1[1], s1[2])

s2 := SplitN(s, unicode.IsSpace, 0)
fmt.Printf("[len=%v: -%v-]\n", len(s2), s2[0])

s3 := SplitN(s, unicode.IsSpace, 1)
fmt.Printf("[len=%v: -%v-%v-]\n", len(s3), s3[0], s3[1])

s4 := SplitN(s, unicode.IsSpace, 5)
if len(s4) == 3 {
	fmt.Printf("[len=%v: -%v-%v-%v-]\n", len(s1), s1[0], s1[1], s1[2])
}

fmt.Println(len(SplitSpace("   ")))
Output:

[len=3: -1-2-3-]
[len=1: -   1   2   3   -]
[len=2: -1-2   3   -]
[len=3: -1-2-3-]
0

func SplitSpace

func SplitSpace(s string) []string

SplitSpace splits the string of s by the whitespace, which is equal to str.split() in Python.

Notice: SplitSpace(s) == Split(s, unicode.IsSpace).

Example
s := "   1   2   3   "
ss := SplitSpace(s)
fmt.Printf("[len=%v: %v-%v-%v]\n", len(ss), ss[0], ss[1], ss[2])
Output:

[len=3: 1-2-3]

func SplitSpaceN

func SplitSpaceN(s string, maxsplit int) []string

SplitSpaceN is the same as SplitStringN, but the whitespace.

func SplitString

func SplitString(s string, sep string) []string

SplitString splits the string of s by sep, but is not the same as strings.Split(), which the rune in sep arbitrary combination. For example, SplitString("abcdefg-12345", "3-edc") == []string{"ab", "fg", "12", "45"}.

Example
s := "abcdefg-12345"
ss := SplitString(s, "3-edc")
fmt.Printf("[len=%v: %v-%v-%v-%v]\n", len(ss), ss[0], ss[1], ss[2], ss[3])
Output:

[len=4: ab-fg-12-45]

func SplitStringN

func SplitStringN(s string, sep string, maxsplit int) []string

SplitStringN is the same as SplitN, but the separator is the string of sep.

func WriteString

func WriteString(w io.Writer, s string, quote ...bool) (n int, err error)

WriteString writes s into w.

Notice: it will escape the double-quotation.

Types

type Builder

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

Builder is a thin wrapper around a byte slice. It's intended to be pooled, so the only way to construct one is via a Pool.

func NewBuilder

func NewBuilder(n int) *Builder

NewBuilder returns a new Builder with a initial capacity n.

func NewBuilderBytes

func NewBuilderBytes(buf []byte) *Builder

NewBuilderBytes returns a new Builder with a initial data.

func NewBuilderString

func NewBuilderString(s string) *Builder

NewBuilderString returns a new Builder with a initial string.

func (*Builder) AppendAny

func (b *Builder) AppendAny(any interface{}) (ok bool, err error)

AppendAny appends any value to the underlying buffer.

It supports the type:

nil     ==> "<nil>"
bool    ==> "true" or "false"
[]byte
string
float32
float64
int
int8
int16
int32
int64
uint
uint8
uint16
uint32
uint64
time.Time ==> time.RFC3339Nano
Slice
Map
interface error
interface io.WriterTo
interface fmt.Stringer
interface encoding.TextMarshaler

For the unknown type, it does not append it and return false, or return true.

Notice: for map[string]interface{} and map[string]string, they are optimized, so the order that the key-value is output is not determined.

func (*Builder) AppendAnyFmt

func (b *Builder) AppendAnyFmt(any interface{}) error

AppendAnyFmt is the same as AppendAny(any), but it will use `fmt.Sprintf("%+v", any)` to format the unknown type `any`.

func (*Builder) AppendBool

func (b *Builder) AppendBool(v bool)

AppendBool appends a bool to the underlying buffer.

func (*Builder) AppendByte

func (b *Builder) AppendByte(c byte)

AppendByte is the same as WriteByte, but no return.

func (*Builder) AppendFloat

func (b *Builder) AppendFloat(f float64, bitSize int)

AppendFloat appends a float to the underlying buffer. It doesn't quote NaN or +/- Inf.

func (*Builder) AppendInt

func (b *Builder) AppendInt(i int64)

AppendInt appends an integer to the underlying buffer (assuming base 10).

func (*Builder) AppendJSON

func (b *Builder) AppendJSON(value interface{}) error

AppendJSON appends the value as the JSON value, that's, the value will be encoded to JSON and appended into the underlying byte slice.

func (*Builder) AppendJSONString

func (b *Builder) AppendJSONString(s string)

AppendJSONString appends a string as JSON string, which will escape the double quotation(") and enclose it with a pair of the double quotation.

func (*Builder) AppendString

func (b *Builder) AppendString(s string)

AppendString is the same as WriteString, but no return.

func (*Builder) AppendTime

func (b *Builder) AppendTime(t time.Time, layout string)

AppendTime appends a time to the underlying buffer.

func (*Builder) AppendUint

func (b *Builder) AppendUint(i uint64)

AppendUint appends an unsigned integer to the underlying buffer (assuming base 10).

func (*Builder) Bytes

func (b *Builder) Bytes() []byte

Bytes returns a mutable reference to the underlying byte slice.

func (*Builder) Cap

func (b *Builder) Cap() int

Cap returns the capacity of the underlying byte slice.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the length of the underlying byte slice.

func (*Builder) Reset

func (b *Builder) Reset()

Reset resets the underlying byte slice.

Subsequent writes will re-use the slice's backing array.

func (*Builder) ResetBytes

func (b *Builder) ResetBytes(bs []byte)

ResetBytes resets the underlying byte slice to bs.

func (*Builder) String

func (b *Builder) String() string

String returns a string copy of the underlying byte slice.

func (*Builder) TrimNewline

func (b *Builder) TrimNewline()

TrimNewline trims any final "\n" byte from the end of the buffer.

func (*Builder) TruncateAfter

func (b *Builder) TruncateAfter(n int)

TruncateAfter truncates and discards last n bytes.

It will is equal to reset if n is greater than the length of the underlying byte slice,

func (*Builder) TruncateBefore

func (b *Builder) TruncateBefore(n int)

TruncateBefore truncates and discards first n bytes.

It will is equal to reset if n is greater than the length of the underlying byte slice,

func (*Builder) Write

func (b *Builder) Write(bs []byte) (int, error)

Write implements io.Writer.

func (*Builder) WriteByte

func (b *Builder) WriteByte(c byte) error

WriteByte writes a byte into the builder.

func (*Builder) WriteRune

func (b *Builder) WriteRune(r rune) (int, error)

WriteRune writes a rune into the builder.

func (*Builder) WriteString

func (b *Builder) WriteString(s string) (int, error)

WriteString writes a string into the builder.

func (*Builder) WriteTo

func (b *Builder) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo.

type Format

type Format struct {
	Left  string
	Right string
}

Format is used to format a string based on the key placeholder that is replaced by the value.

Example
format := NewFormat("{{", "}}")

s1 := format.Format("hello {{name}}. {{name}}.", "name", "world")
fmt.Println(s1)

s2 := format.Format("hello {{name}}. {{name}}.", "name", "world", "age", 123)
fmt.Println(s2)

s3 := format.Format("hello {{name}}. {{name}}.", "age", 123)
fmt.Println(s3)

s4 := format.FormatByMap("hello {{name}}. {{name}}.", map[string]interface{}{"name": "world"})
fmt.Println(s4)

s5 := format.FormatByMap("hello {{name}}. {{name}}.", map[string]interface{}{"name": "world", "age": 123})
fmt.Println(s5)

s6 := format.FormatByMap("hello {{name}}. {{name}}.", map[string]interface{}{"age": 123})
fmt.Println(s6)

s7 := format.FormatByMap("hello {{name}}. You are [{{age:6d}}].", map[string]interface{}{"name": "world", "age": 123})
fmt.Println(s7)

s8 := format.Format("hello {{name}}. You are [{{age:6d}}].", "name", "world", "age", 123)
fmt.Println(s8)

s9 := format.Format("hello {{name}}.", "name", func() interface{} { return "world" })
fmt.Println(s9)

s10 := format.FormatByFunc("hello {{name}}.", func(key string) (interface{}, bool) {
	switch key {
	case "name":
		return "world", true
	default:
		return nil, false
	}
})
fmt.Println(s10)
Output:

hello world. world.
hello world. world.
hello {{name}}. {{name}}.
hello world. world.
hello world. world.
hello {{name}}. {{name}}.
hello world. You are [   123].
hello world. You are [   123].
hello world.
hello world.

func NewFormat

func NewFormat(left, right string) Format

NewFormat returns a new Format.

func (Format) Format

func (f Format) Format(s string, kwargs ...interface{}) string

Format formats the string s, which will convert kwargs to map[string]interface{} and call the method FormatByMap().

Notice: the number of kwargs must be even, and the odd argument must be string.

func (Format) FormatByFunc

func (f Format) FormatByFunc(s string, getValue func(key string) (interface{}, bool)) string

FormatByFunc is the same as FormatByFunc, but returns the result string.

func (Format) FormatByMap

func (f Format) FormatByMap(s string, kwargs map[string]interface{}) string

FormatByMap is the same as FormatByFunc, which will get the value from kwargs.

func (Format) FormatOutput

func (f Format) FormatOutput(w io.Writer, s string, getValue func(key string) (interface{}, bool)) (n int, err error)

FormatOutput formats the string s into w, which will replaces the placeholder key with the value returned by getValue(key).

If the placeholder key does not have a corresponding value, it will persist and not be replaced. However, if the value is a function, func() interface{}, it will call it firstly to calculate the value.

The placeholder key maybe contain the formatter, and the value will be formatted by fmt.Sprintf(formatter, value). They are separated by the colon and the % character is optional.

type StringWriter

type StringWriter interface {
	WriteString(string) (int, error)
}

StringWriter is a WriteString interface.

Jump to

Keyboard shortcuts

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