stringx

package module
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 11 Imported by: 7

README

stringx

stringx provides String type based on functional programming

The original code for the stringx package was analyzed at golang strings package.

The function signatures and core logic were replicated and adapted.

Modifications were made to improve readability, performance, or to suit specific projects.

All credits for the original code belong to the Go team, whose code is licensed under the BSD-style license.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnreadRuneAtBeginning is returned by [github.com/i9si-sistemas/stringx.Reader.UnreadRune] when the reader is at the beginning of the string.
	ErrUnreadRuneAtBeginning = errors.New("stringx.Reader.UnreadRune: at beginning of string")

	// ErrUnreadRuneNotRead is returned by [github.com/i9si-sistemas/stringx.Reader.UnreadRune] when the previous operation was not ReadRune.
	ErrUnreadRuneNotRead = errors.New("stringx.Reader.UnreadRune: previous operation was not ReadRune")
)
View Source
var (
	// ErrSeekInvalidWhence is returned by [github.com/i9si-sistemas/stringx.Reader.Seek] when the whence argument is invalid.
	ErrSeekInvalidWhence = errors.New("stringx.Reader.Seek: invalid whence")

	// ErrSeekNegativePosition is returned by [github.com/i9si-sistemas/stringx.Reader.Seek] when the position is negative.
	ErrSeekNegativePosition = errors.New("stringx.Reader.Seek: negative position")
)
View Source
var (
	// Space is the space character.
	Space = String(" ")

	// Dash is the dash character.
	Dash = String("-")

	// Zero is the zero character
	Zero = String("0")

	// Equals is the equals character
	Equals = String("=")

	// Tab is the tab character.
	Tab = String("\t")

	// Plus is the plus character.
	Plus = String("+")

	// NewLine is the newline character.
	NewLine = String("\n")
)
View Source
var (
	// ErrOldOrNewCannotBeEmpty is returned when either old or new slice is empty.
	ErrOldOrNewCannotBeEmpty = errors.New("stringx: old or new cannot be empty")
	// ErrOldAndNewMustHaveSameLen is returned when old and new slice have different length.
	ErrOldAndNewMustHaveSameLen = errors.New("stringx: old and new must have the same length")
)
View Source
var Empty = String("")

Empty is an empty string.

View Source
var ErrInvalidExpression = MathError("Invalid expression")

ErrInvalidExpression is returned when the expression is invalid.

View Source
var ErrReadAtNegativeOffset = errors.New("stringx.Reader.ReadAt: negative offset")

ErrReadAtNegativeOffset is returned by github.com/i9si-sistemas/stringx.Reader.ReadAt when the offset is negative.

View Source
var ErrReaderEOF = io.EOF

ErrReaderEOF is returned when the reader reaches the end of the string.

View Source
var ErrUnreadByte = errors.New("stringx.Reader.UnreadByte: at beginning of string")

ErrUnreadByte is returned by github.com/i9si-sistemas/stringx.Reader.UnreadByte when the reader is at the beginning of the string.

View Source
var ErrWriteToInvalidWriteStringCount = errors.New(
	"stringx.Reader.WriteTo: invalid WriteString count",
)

ErrWriteToInvalidWriteStringCount is returned by github.com/i9si-sistemas/stringx.Reader.WriteTo when the number of bytes written is not equal to the length of the string.

View Source
var Log = log.Println

Log is default printer for stringx.

Functions

func IndexOf added in v1.5.9

func IndexOf(s, substr string) int

IndexOf returns the index of the first occurrence of substr in s, or -1 if substr is not present in s.

func IsEmpty added in v1.5.9

func IsEmpty(s string) bool

IsEmpty checks if the given string is empty.

func IsEqual added in v1.5.9

func IsEqual(s, value string) bool

IsEqual checks if two strings are equal.

Types

type Builder

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

A Builder is used to efficiently build a string using Write methods.

func NewBuilder

func NewBuilder(buf ...byte) *Builder

NewBuilder returns a new Builder.

func (*Builder) Cap

func (b *Builder) Cap() int

Cap returns the capacity of the builder's underlying byte slice. It is the total space allocated for the string being built and includes any bytes already written.

func (*Builder) Grow

func (b *Builder) Grow(n int)

Grow grows b's capacity, if necessary, to guarantee space for another n bytes.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the number of accumulated bytes

func (*Builder) String

func (b *Builder) String() string

String returns the accumulated string.

func (*Builder) Write

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

Write appends the contents of p to b's buffer. Write always returns len(p), nil.

func (*Builder) WriteByte

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

WriteByte appends the byte c to b's buffer. The returned error is always nil.

func (*Builder) WriteRune

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

WriteRune appends the UTF-8 encoding of Unicode code point r to b's buffer. It returns the length of r and a nil error.

func (*Builder) WriteString

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

WriteString appends the contents of s to b's buffer. It returns the length of s and a nil error.

type Case

type Case int

Case represents the case of a string.

const (
	// Upper represents the upper case.
	Upper Case = iota
	// Lower represents the lower case.
	Lower
)

type MapFn added in v1.5.9

type MapFn func(r rune) rune

MapFn defines a function type that takes a rune and returns a rune.

type MathError added in v1.5.2

type MathError string

MathError is a math error.

func (MathError) Error added in v1.5.2

func (e MathError) Error() string

type Number added in v1.5.2

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

Number is a string wrapper for number.

func ParseNumber added in v1.5.2

func ParseNumber(s string) Number

ParseNumber returns a Number object.

func (Number) Float added in v1.5.2

func (s Number) Float() float64

Float returns the number as float64.

func (Number) Float32 added in v1.5.2

func (s Number) Float32() float32

Float32 returns the number as float32.

func (Number) Int added in v1.5.2

func (s Number) Int() int

Int returns the number as int.

func (Number) Int16 added in v1.5.2

func (s Number) Int16() int16

Int16 returns the number as int16.

func (Number) Int32 added in v1.5.2

func (s Number) Int32() int32

Int32 returns the number as int32.

func (Number) Int64 added in v1.5.2

func (s Number) Int64() int64

Int64 returns the number as int64.

func (Number) Int8 added in v1.5.2

func (s Number) Int8() int8

Int8 returns the number as int8.

func (Number) String added in v1.5.2

func (s Number) String() string

String returns the number string.

func (Number) Uint added in v1.5.2

func (s Number) Uint() uint

Uint returns the number as uint.

func (Number) Uint16 added in v1.5.2

func (s Number) Uint16() uint16

Uint16 returns the number as uint16.

func (Number) Uint32 added in v1.5.2

func (s Number) Uint32() uint32

Uint32 returns the number as uint32.

func (Number) Uint64 added in v1.5.2

func (s Number) Uint64() uint64

Uint64 returns the number as uint64.

func (Number) Uint8 added in v1.5.2

func (s Number) Uint8() uint8

Uint8 returns the number as uint8.

type Parser added in v1.5.2

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

Parser is a string parser.

func NewParser added in v1.5.2

func NewParser(s string) *Parser

NewParser creates a github.com/i9si-sistemas/stringx.Parser.

func (*Parser) Bool added in v1.5.2

func (p *Parser) Bool() (bool, error)

Bool parses a bool-comparison or a plain bool literal.

func (*Parser) Float added in v1.5.2

func (p *Parser) Float() (n float64, err error)

Float parses a float.

func (*Parser) Int added in v1.5.2

func (p *Parser) Int() (n int64, err error)

Int parses an integer.

type Random added in v1.5.0

type Random interface {
	// Index returns a valid random index based on the collection size.
	Index() int
	// MaxLength returns the maximum size of the string collection.
	MaxLength() int
	// Random returns a random string from the collection.
	Random() String
}

Random defines an interface for selecting a random element from a string collection.

func NewRandomString added in v1.5.0

func NewRandomString(s ...string) Random

NewRandomString creates a new Random instance from a list of strings.

type Reader added in v1.4.0

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

A Reader implements the io.Reader, io.ReaderAt, io.ByteReader, io.ByteScanner, io.RuneReader, io.RuneScanner, io.Seeker, and io.WriterTo interfaces by reading from a string. The zero value for Reader operates like a Reader of an empty string.

func NewReader added in v1.4.0

func NewReader(s string) *Reader

NewReader returns a new github.com/i9si-sistemas/stringx.Reader reading from s. It is similar to bytes.NewBufferString but more efficient and non-writable.

func (*Reader) Len added in v1.4.0

func (r *Reader) Len() int

Len returns the number of bytes of the unread portion of the string.

func (*Reader) Read added in v1.4.0

func (r *Reader) Read(b []byte) (n int, err error)

Read implements the io.Reader interface.

func (*Reader) ReadAt added in v1.4.0

func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

ReadAt implements the io.ReaderAt interface.

func (*Reader) ReadByte added in v1.4.0

func (r *Reader) ReadByte() (byte, error)

ReadByte implements the io.ByteReader interface.

func (*Reader) ReadRune added in v1.4.0

func (r *Reader) ReadRune() (ch rune, size int, err error)

ReadRune implements the io.RuneReader interface.

func (*Reader) Reset added in v1.4.0

func (r *Reader) Reset(s string)

Reset resets the github.com/i9si-sistemas/stringx.Reader to be reading from s.

func (*Reader) Seek added in v1.4.0

func (r *Reader) Seek(offset int64, whence int) (int64, error)

Seek implements the io.Seeker interface.

func (*Reader) Size added in v1.4.0

func (r *Reader) Size() int64

Size returns the original length of the underlying string. Size is the number of bytes available for reading via github.com/i9si-sistemas/stringx.Reader.ReadAt. The returned value is always the same and is not affected by calls to any other method.

func (*Reader) UnreadByte added in v1.4.0

func (r *Reader) UnreadByte() error

UnreadByte implements the io.ByteScanner interface.

func (*Reader) UnreadRune added in v1.4.0

func (r *Reader) UnreadRune() error

UnreadRune implements the io.RuneScanner interface.

func (*Reader) WriteTo added in v1.4.0

func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements the io.WriterTo interface.

type Replacer added in v1.1.2

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

Replacer is a struct that holds a String and two slices of strings for replacement.

func NewReplacer added in v1.1.2

func NewReplacer(s String, old []string, new []string) *Replacer

NewReplacer creates a new Replacer instance with the provided String and slices of old and new strings.

func (*Replacer) Replace added in v1.1.2

func (r *Replacer) Replace() (string, error)

Replace performs the replacement of old strings with new strings in the String.

type ReverseFn added in v1.5.6

type ReverseFn func(index int) String

type String

type String string

String is a functional string type.

func Convert

func Convert(s Stringer) String

Convert converts a Stringer to a String.

Example:

type Slice []any
func (s Slice) String() string {
	return fmt.Sprintf("%v", s)
}
slice := Slice{1, 2, 3}
s := Convert(slice)

func Map added in v1.5.9

func Map(s String, fn MapFn) String

Map applies a function to each rune in the string, returning a new string

func New added in v1.6.0

func New(s any) String

New creates a new String from any type that implements Stringer or is a string.

stringx.New("hello") // String("hello")
stringx.New([]byte("hello")) // String("hello")
type NumberStr int
func (n NumberStr) String() string { return fmt.Sprint(n) }
stringx.New(NumberStr(123)) // String("123")

func (String) Builder

func (s String) Builder() *Builder

Builder returns a new stringx.Builder.

func (String) Bytes

func (s String) Bytes() []byte

Bytes returns the byte slice representation of the String.

func (String) CharAt

func (s String) CharAt(index int) String

CharAt returns the character at the given index.

func (String) Concat

func (s String) Concat(str ...Stringer) String

Concat concatenates the String with other Stringers.

func (String) ConcatStrings added in v1.5.4

func (s String) ConcatStrings(str ...string) String

ConcatStrings concatenates the String with other strings.

func (String) Count

func (s String) Count(value string) int

Count returns the number of non-overlapping instances of substr in s.

func (String) Equal added in v1.2.0

func (s String) Equal(value string) bool

Equal checks if the string is equal to the given value.

func (String) HasPrefix

func (s String) HasPrefix(prefix string) bool

HasPrefix checks if the string starts with the specified prefix.

func (String) HasSuffix added in v1.4.2

func (s String) HasSuffix(suffix string) bool

HasSuffix reports whether s ends with suffix.

func (String) Includes

func (s String) Includes(substr string) bool

Includes checks if the string s contains the substring substr.

func (String) IndexOf

func (s String) IndexOf(substr string) int

IndexOf returns the index of the first occurrence of substr in s, or -1 if substr is not present in s.

func (String) IsEmpty

func (s String) IsEmpty() bool

IsEmpty returns true if the string is empty.

func (String) Length

func (s String) Length() int

Length returns the length of the string.

func (String) Lines added in v1.4.3

func (s String) Lines() iter.Seq[string]

Lines returns an iterator over the newline-terminated lines in the string s.

func (String) Map

func (s String) Map(fn MapFn) String

Map applies a function to each rune in the string, returning a new string

func (String) Match

func (s String) Match(regex string) bool

func (String) Repeat

func (s String) Repeat(value string, count int) String

Repeat returns a new String by repeating the specified `value` string `count` times and concatenating the result to the original String `s`.

example:

String("Go").Repeat("lang", 3) // returns "Golanglanglang"

Parameters:

value - the string to repeat
count - the number of times to repeat the value

Returns:

A new String with the repeated value appended to the original.

func (String) Replace

func (s String) Replace(old, new string) String

Replace performs the replacement of old strings with new strings in the String.

func (String) Reverse added in v1.5.5

func (s String) Reverse() (result String)

func (String) ReverseFn added in v1.5.6

func (s String) ReverseFn(fn ReverseFn) (result String)

func (String) Runes

func (s String) Runes() []rune

Runes returns the rune slice representation of the String.

func (String) Search

func (s String) Search(regex string) []string

func (String) Slice

func (s String) Slice(start, end int) String

Slice returns a substring of the String from start to end indices.

func (String) Split

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

Split splits the string s into substrings separated by sep.

func (String) SplitN added in v1.4.1

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

SplitN splits the string s into substrings separated by sep.

  • sep: the separator.
  • n: the maximum number of substrings to return.

Example:

s := stringx.String("Hello, World !")
s.SplitN(stringx.Space.String(), 2) // ["Hello", "World !"]

func (String) String

func (s String) String() string

String returns the string representation of the String.

func (String) ToLowerCase

func (s String) ToLowerCase() String

ToLowerCase converts the string to lower case. It uses the unicode.ToLower function to ensure proper handling of Unicode characters.

func (String) ToUpperCase

func (s String) ToUpperCase() String

ToUpperCase converts the string to upper case. It uses the unicode.ToUpper function to ensure proper handling of Unicode characters.

func (String) Trim

func (s String) Trim(cutset string) (result String)

Trim removes all leading and trailing characters in cutset from the string.

func (String) TrimEnd

func (s String) TrimEnd(cutset string) (result String)

TrimEnd removes all trailing characters in cutset from the string.

func (String) TrimPrefix added in v1.4.2

func (s String) TrimPrefix(prefix string) (result String)

TrimPrefix removes all leading characters in prefix from the string.

func (String) TrimStart

func (s String) TrimStart(cutset string) (result String)

TrimStart removes all leading characters in cutset from the string.

func (String) TrimSuffix added in v1.4.2

func (s String) TrimSuffix(suffix string) (result String)

TrimSuffix removes all trailing characters in suffix from the string.

type Stringer

type Stringer interface {
	// String returns the string representation of the object.
	String() string
}

Stringer is an interface that can be converted to a string.

type Strings

type Strings []String

func ConvertMany

func ConvertMany(s ...Stringer) Strings

func ConvertStrings added in v1.1.2

func ConvertStrings(s ...string) Strings

func (Strings) Join

func (s Strings) Join(sep string) String

func (Strings) Random added in v1.5.0

func (s Strings) Random(r Random) String

Random selects a random string from the collection s using the index provided by r.

Jump to

Keyboard shortcuts

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