strings

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2023 License: MIT Imports: 12 Imported by: 0

README

Go Reference

Functional Strings

This package has functions for working with strings, runes, and types that are based on them. Many of them are just wrapping functions from the standard strings package, strconv, or golang.org/x/text/cases but uses generics so casting is unnecessary for types based on strings or runes and some can work on either strings or runes.

Get it

go get -u github.com/flowonyx/functional/strings

Use it

import "github.com/flowonyx/functional/strings"

Types

The types from the standard library's strings package are aliased in this package so we can just import the one package.

Functions

Because most of the functions are just wrapping the functions from the standard strings package, I will just note some of the functions here.

  • Collect accepts a function which maps each rune in the given string to a string, then concatenates them together into one string.
  • Collecti: the difference between Collecti and Collect is that the mapping function receives the index of the rune.
  • Concat concatenates a list of strings or runes into one string.
  • Exists checks for the existence of a rune within a string that matches a predicate function.
  • Filter returns a string built from the given string that only contains runes matching a predicate function.
  • ForAll checks whether every rune in a given string matches a predicate function.
  • InitString creates a string of a given length where each rune is initialized by an initializer function.
  • Iter performs an action for each rune in a string, passing the rune to the action function.
  • Iteri performs an action for each rune in a string, passing the rune and its index to the action function.
  • Join joins items of any type into a string of values separated by whatever string or rune you choose.
    • It uses fmt.Sprint to represent each elem as a string.
    • If you are passing runes or strings, it is slightly faster to call JoinRunes or JoinStrings instead.
  • LastIndexRune returns the index of the last instance of a rune in a string, or -1 if it is not present.
  • Lines splits a string on newline boundaries into a slice of strings. The results do not include the newlines.
  • GetLine gets the value of a specific line in a string indicated by index. An error is returned if the index is out of range.
    • Use GetLineOpt when you want an option.Option instead of an error.
  • Lower returns a string with all lowercase letters based on the English language.
    • If you need to use another language, call LowerSpecialCase directly.
  • Mapi does the same as Map except that the mapping function is supplied with the index of the rune within the string along with the rune.
    • If mapping returns a negative value, the character is dropped from the string with no replacement.
  • Range creates a slice of runes that between the start and end runes (inclusive).
    • Range('A', 'C') would create []rune{'A', 'B', 'C'}.
  • Title returns a string with English title casing. It uses an approximation of the default Unicode Word Break algorithm.
    • If you want to have the title casing specific to another language, use TitleSpecial instead.
  • Upper returns a string with English upper casing. It uses an approximation of the default Unicode Word Break algorithm.
    • If you want to have the upper casing specific to another language, use UpperSpecial instead.
  • Unquote wraps strconv.Unquote and just returns the original string in case of an error.

Documentation

Overview

Package strings provides methods that work on strings or runes--but also types descended from them. Where possible, the functions take either a string or a rune. Most, if not all, functions from the standard "strings" package are replicated here, but with generic inputs.

Index

Examples

Constants

View Source
const (
	YYYYMMDD         = "2006-01-02"
	YYYYMMDDNoDashes = "20060102"
	YYYYMD           = "2006-1-2"
	MMDDYYYY         = "01-02-2006"
	MMDDYYYYNoDashes = "01022006"
	MDYYYY           = "1-2-2006"
	MDYYYYName       = "Jan 2, 2006"
	MDYYYYFullName   = "January 2, 2006"

	HHmmss = ""
)

Common date formats.

Variables

This section is empty.

Functions

func CamelCaseToUnderscore

func CamelCaseToUnderscore[TString ~string](camel TString) TString

CamelCaseToUnderscore converts camel case strings to its equivalent as underscore separated.

Example
s := CamelCaseToUnderscore("exampleString")
fmt.Print(s)
Output:

example_string

func Clone

func Clone[TString ~string](s TString) TString

Clone returns a fresh copy of s. It guarantees to make a copy of s into a new allocation, which can be important when retaining only a small substring of a much larger string. Using Clone can help such programs use less memory. Of course, since using Clone makes a copy, overuse of Clone can make programs use more memory. Clone should typically be used only rarely, and only when profiling indicates that it is needed. For strings of length zero the string "" will be returned and no allocation is made.

func Collect

func Collect[TString1, TString2 ~string, TRune ~rune](mapping func(TRune) TString2, str TString1) TString1

Collect accepts a function which maps each rune in the given string to a string, then concatenates them together into one string. If str is a descendant of string the actual type of str will be returned.

Example
input := "12345"
r := Collect(func(r rune) string {
	i, err := ToInt(r)
	if err != nil {
		return err.Error()
	}
	return Repeat(r, i)
}, input)
fmt.Println(r)
Output:

122333444455555

func Collecti

func Collecti[TString1, TString2 ~string, TRune ~rune](mapping func(int, TRune) TString2, str TString1) TString1

Collecti accepts a function which maps each rune in the given string to a string, then concatenates them together into one string. If str is a descendant of string the actual type of str will be returned. The difference between Collecti and Collect is that the mapping function receives the index of the rune.

Example
input := "12345"
r := Collecti(func(i int, r rune) string {
	return Repeat(r, i)
}, input)
fmt.Println(r)
Output:

2334445555

func Compare

func Compare[TString1, TString2 StringOrRune](a TString1, b TString2) int

Compare returns an integer comparing two strings lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b. Compare is included only for symmetry with package bytes. It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, and so on.

func Concat

func Concat[T StringOrRune](s []T) string

Concat concatenates a list of strings or runes into one string.

Example
input := []string{
	"hello",
	" ",
	"world",
}
r := Concat(input)
fmt.Println(r)
Output:

hello world

func Contains

func Contains[TString1, TString2 StringOrRune](s TString1, substr TString2) bool

Contains reports whether substr is within s.

func ContainsAny

func ContainsAny[TString1, TString2 StringOrRune](s TString1, chars TString2) bool

ContainsAny reports whether any Unicode code points in chars are within s.

func ContainsRune

func ContainsRune[TString ~string, TRune ~rune](s TString, r TRune) bool

ContainsRune reports whether the Unicode code point r is within s.

func Count

func Count[TString1, TString2 StringOrRune](s TString1, substr TString2) int

Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.

func Cut

func Cut[TString ~string, TSep StringOrRune](s TString, sep TSep) (before, after TString, found bool)

Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s. If sep does not appear in s, cut returns s, "", false.

func EqualFold

func EqualFold[TString1, TString2 StringOrRune](s TString1, t TString2) bool

EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under Unicode case-folding, which is a more general form of case-insensitivity.

func Exists

func Exists[TString ~string, TRune ~rune](predicate func(TRune) bool, str TString) bool

Exists checks for the existence of a rune within str that matches the predicate.

Example
input := "12345"
ft := func(r rune) bool { return r < '5' }
ff := func(r rune) bool { return r > '5' }
r1 := Exists(ft, input)
r2 := Exists(ff, input)
fmt.Printf("%t, %t", r1, r2)
Output:

true, false

func Fields

func Fields[TString ~string](s TString) []TString

Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.

func FieldsFunc

func FieldsFunc[TString ~string, TRune ~rune](dividerPredicate func(TRune) bool, s TString) []TString

FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) and returns an array of slices of s. If all code points in s satisfy f(c) or the string is empty, an empty slice is returned. FieldsFunc makes no guarantees about the order in which it calls f(c) and assumes that f always returns the same value for a given c.

func Filter

func Filter[TString ~string, TRune ~rune](predicate func(TRune) bool, str TString) TString

Filter returns a string built from str that only contains runes matching the predicate.

Example
input := "12345"
r := Filter(func(r rune) bool { return r < '4' }, input)
fmt.Println(r)
Output:

123

func Fold

func Fold[TString ~string](s TString) TString

Fold implements Unicode case folding. Case folding does not normalize the input and may not preserve a normal form. Use the collate or search package for more convenient and linguistically sound comparisons. Use golang.org/x/text/secure/precis for string comparisons where security aspects are a concern.

func ForAll

func ForAll[TString ~string, TRune ~rune](predicate func(TRune) bool, str TString) bool

ForAll checks whether every rune in str matches the predicate.

func FromBool

func FromBool[TBool ~bool](b TBool) string

FromBool converts a bool into either "True" or "False".

Example
t := FromBool(true)
f := FromBool(false)
fmt.Printf("%s, %s", t, f)
Output:

true, false

func FromFloat

func FromFloat[TFloat constraints.Float](f TFloat) string

FromFloat converts a float to a string.

Example
s := FromFloat(123.4)
fmt.Println(s)
Output:

123.4

func FromInt

func FromInt[TInt constraints.Integer](i TInt) string

FromInt converts an integer value to a string.

Example
s1 := FromInt(-1)
s2 := FromInt(1025)

fmt.Printf("%s | %s", s1, s2)
Output:

-1 | 1025

func FromRunes

func FromRunes[TRune ~rune](input []TRune) string

FromRunes simply creates a string from the given runes. It is faster to just call string(input) instead, but sometimes it is convenient to have a function that can be passed around.

func GetLine

func GetLine[TString ~string, TInt constraints.Integer](s TString, index TInt) (TString, error)

GetLine gets the value of the line in s indicated by index. An error is returned if the index is out of range.

Example
input := "line1\nline2\rline3\r\nline4"
r, err := GetLine(input, 2)
if err != nil {
	panic(err)
}
fmt.Println(Quote(r))
Output:

"line3"

func GetLineOpt

func GetLineOpt[TString ~string, TInt constraints.Integer](s TString, index TInt) option.Option[TString]

GetLineOpt gets the value of the line in s indicated by index. None is returned if the index is out of range.

Example
input := "line1\nline2\rline3\r\nline4"
r := GetLineOpt(input, 4)
fmt.Println(r)
Output:

None

func HasPrefix

func HasPrefix[TString, TPrefix StringOrRune](s TString, prefix TPrefix) bool

HasPrefix tests whether the string s begins with prefix.

func HasSuffix

func HasSuffix[TString, TSuffix StringOrRune](s TString, prefix TSuffix) bool

HasSuffix tests whether the string s ends with suffix.

func Index

func Index[TString1, TString2 StringOrRune](s TString1, substr TString2) int

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

func IndexAny

func IndexAny[TString1, TString2 StringOrRune](s TString1, chars TString2) int

IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

func IndexByte

func IndexByte[TString1 StringOrRune, TByte ~byte](s TString1, c TByte) int

IndexByte returns the index of the first instance of c in s, or -1 if c is not present in s.

func IndexFunc

func IndexFunc[TString1 StringOrRune](s TString1, f func(rune) bool) int

IndexByte returns the index of the first instance of c in s, or -1 if c is not present in s.

func IndexRune

func IndexRune[TString1 StringOrRune, TRune ~rune](s TString1, r TRune) int

IndexRune returns the index of the first instance of the Unicode code point r, or -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

func InitString

func InitString[TString ~string, TInt1, TInt2 constraints.Integer](count TInt1, initializer func(TInt2) TString) TString

InitString creates a string of length count where each rune is initialized by the initializer function.

Example
r := InitString(5, func(i int) string { return FromInt(i) })
fmt.Println(r)
Output:

01234

func IsDate

func IsDate[TString ~string](s TString, formats ...string) bool

IsDate checks if the given string is a date according to either the given format(s) or the default formats if none are provided.

Example
t := IsDate("2000-1-1")
f := IsDate("1-1-1")
fmt.Printf("%t, %t", t, f)
Output:

true, false

func IsEmail

func IsEmail[TString ~string](s TString) bool

IsEmail checks if the given string can be parsed as an email address.

Example
t1 := IsEmail("test@test.com")
t2 := IsEmail("\"Tester\" <test@test.com>")
f := IsEmail("@handle")
fmt.Printf("%t, %t, %t", t1, t2, f)
Output:

true, true, false

func Iter

func Iter[TString ~string, TRune ~rune](action func(TRune), str TString)

Iter performs an action for each rune in str, passing the rune to the action function.

Example
input := "12345"
s := ""
Iter(func(r rune) {
	s += Repeat(r, 2)
}, input)
fmt.Println(s)
Output:

1122334455

func Iteri

func Iteri[TString ~string](action func(int, rune), str TString)

Iteri performs an action for each rune in str, passing the index and the rune to the action function.

Example
input := "12345"
s := ""
Iteri(func(i int, r rune) {
	s += Repeat(r, i)
}, input)
fmt.Println(s)
Output:

2334445555

func Join

func Join[TSep StringOrRune, T any](elems []T, sep TSep) string

Join joins elems of any type into a string of sep separated values. It uses fmt.Sprint to represent each elem as a string. If you are passing runes or strings, it is slightly faster to call JoinRunes or JoinStrings instead.

Example
input := []int{1, 2, 3}
s := Join(input, ", ")
fmt.Println(s)
Output:

1, 2, 3

func JoinRunes

func JoinRunes[TSep StringOrRune, TRune ~rune](elems []TRune, sep TSep) string

JoinRunes joins runes into a string of sep seprated values. If you are trying to join them without a separator, use Concat or simply string(elems) instead.

Example
input := []rune{'a', 'b', 'c'}
s := JoinRunes(input, ", ")
fmt.Println(s)
Output:

a, b, c

func JoinStrings

func JoinStrings[TSep StringOrRune, TString ~string](elems []TString, sep TSep) string

JoinStrings joins strings into a string of sep seprated values. If you are trying to join them without a separator, use Concat instead.

Example
input := []string{"a", "b", "c"}
s := JoinStrings(input, ", ")
fmt.Println(s)
Output:

a, b, c

func LastIndex

func LastIndex[TString1, TString2 StringOrRune](s TString1, substr TString2) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

func LastIndexAny

func LastIndexAny[TString1, TString2 StringOrRune](s TString1, chars TString2) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

func LastIndexByte

func LastIndexByte[TString1 StringOrRune, TByte ~byte](s TString1, c TByte) int

LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.

func LastIndexFunc

func LastIndexFunc[TString1 StringOrRune](s TString1, f func(rune) bool) int

LastIndexFunc returns the index into s of the last Unicode code point satisfying f(c), or -1 if none do.

func LastIndexRune

func LastIndexRune[TString1 ~string, TRune ~rune](s TString1, r TRune) int

LastIndexRune returns the index of the last instance of r in s, or -1 if r is not present in s.

Example
input := "abcdeab"
r := LastIndexRune(input, 'b')
fmt.Println(r)
Output:

6

func Lines

func Lines[TString ~string](s TString) []TString

Lines splits s on newline boundaries into a slice of strings. The results do not include the newlines.

Example
input := "line1\nline2\rline3\r\nline4"
r := Lines(input)
fmt.Println(len(r), r)
Output:

4 [line1 line2 line3 line4]

func Lower

func Lower[TString ~string](s TString) TString

Lower returns s with all lowercase letters based on the English language. If you need to use another language, call LowerSpecialCase directly.

func LowerSpecialCase

func LowerSpecialCase[TString ~string](s TString, language language.Tag) TString

LowerSpecialCase uses language specific rules for returning s in lower case.

func Map

func Map[TString ~string, TRune ~rune](mapping func(TRune) TRune, s TString) TString

Map returns a copy of the string s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

func Mapi

func Mapi[TString ~string, TRune ~rune](mapping func(int, TRune) TRune, s TString) TString

Mapi does the same as Map except that the mapping function is supplied with the index of the rune within the string along with the rune. If mapping returns a negative value, the character is dropped from the string with no replacement.

Example
input := "12345"
output := Mapi(func(i int, r rune) rune {
	if i > 2 {
		r = r + 13
	}
	return r
}, input)
fmt.Println(output)
Output:

123AB

func NormalizeNewLine

func NormalizeNewLine(s string) string

NormalizeNewLine replaces any "non-normalized" newlines ("\r\n", '\r') with '\n'.

Example
s := NormalizeNewLine("line1\nline2\r\nline3\rline4")
fmt.Print(Quote(s))
Output:

"line1\nline2\nline3\nline4"

func Quote

func Quote[TString ~string](s TString) TString

Quote returns a double-quoted Go string literal representing s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint.

func QuoteRune

func QuoteRune[TRune ~rune](r TRune) string

QuoteRune returns a single-quoted Go character literal representing the rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint.

func Range

func Range[TRune ~rune](start, end TRune) []TRune

Range creates a slice of runes that between the start and end runes (inclusive). Range('A', 'C') would create []rune{'A', 'B', 'C'}.

Example
r := string(Range('a', 'd'))
fmt.Println(r)
Output:

abcd

func Repeat

func Repeat[TString StringOrRune, TCount constraints.Integer](s TString, count TCount) string

Repeat returns a new string consisting of count copies of the string s. It panics if count is negative or if the result of (len(s) * count) overflows.

func Replace

func Replace[TString1 ~string, TString2, TString3 StringOrRune, TInt constraints.Integer](s TString1, old TString2, new TString3, n TInt) TString1

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

func ReplaceAll

func ReplaceAll[TString1 ~string, TString2, TString3 StringOrRune](s TString1, old TString2, new TString3) TString1

ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.

func RuneIsASCIILetter

func RuneIsASCIILetter[TRune ~rune](r TRune) bool

RuneIsASCIILower checks if the given rune is an ASCII character (either upper or lower case).

Example
t1 := RuneIsASCIILetter('A')
t2 := RuneIsASCIILetter('a')
f := RuneIsASCIILetter('!')
fmt.Printf("%t, %t, %t", t1, t2, f)
Output:

true, true, false

func RuneIsASCIILower

func RuneIsASCIILower[TRune ~rune](r TRune) bool

RuneIsASCIILower checks if the given rune is an ASCII lower case character.

Example
t := RuneIsASCIILower('a')
f := RuneIsASCIILower('A')
fmt.Printf("%t, %t", t, f)
Output:

true, false

func RuneIsASCIIUpper

func RuneIsASCIIUpper[TRune ~rune](r TRune) bool

RuneIsASCIILower checks if the given rune is an ASCII upper case character.

Example
t := RuneIsASCIIUpper('A')
f := RuneIsASCIIUpper('a')
fmt.Printf("%t, %t", t, f)
Output:

true, false

func RuneIsAnyOf

func RuneIsAnyOf[TRune, TRuneList ~rune](runes []TRuneList, r TRune) bool

RuneIsAnyOf checks if the the given rune r is in the given list of runes.

Example
t := RuneIsAnyOf([]rune("123"), '2')
f := RuneIsAnyOf([]rune("123"), '4')
fmt.Printf("%t, %t", t, f)
Output:

true, false

func RuneIsHex

func RuneIsHex[TRune ~rune](r TRune) bool

RuneIsHex checks if the given rune is a valid hexadecimal numeral (0-9, a-f, A-F).

Example
t1 := RuneIsHex('0')
t2 := RuneIsHex('9')
t3 := RuneIsHex('F')
t4 := RuneIsHex('f')
f := RuneIsHex('G')
fmt.Printf("%t, %t, %t, %t, %t", t1, t2, t3, t4, f)
Output:

true, true, true, true, false

func RuneIsNewLine

func RuneIsNewLine[TRune ~rune](r TRune) bool

RuneIsNewLine checks if the given rune is a valid newline character ('\n' or '\r').

Example
t1 := RuneIsNewLine('\n')
t2 := RuneIsNewLine('\r')
f := RuneIsNewLine('\t')
fmt.Printf("%t, %t, %t", t1, t2, f)
Output:

true, true, false

func RuneIsNoneOf

func RuneIsNoneOf[TRune, TRuneList ~rune](runes []TRuneList, r TRune) bool

RuneIsNoneOf checks whether the given rune r is in the given list of runes and returns false if it is present.

Example
t := RuneIsNoneOf([]rune("123"), '4')
f := RuneIsNoneOf([]rune("123"), '2')
fmt.Printf("%t, %t", t, f)
Output:

true, false

func RuneIsOctal

func RuneIsOctal[TRune ~rune](r TRune) bool

RuneIsOctal checks if the given rune is a valid octal numeral (0-7).

Example
t1 := RuneIsOctal('0')
t2 := RuneIsOctal('7')
f := RuneIsOctal('8')
fmt.Printf("%t, %t, %t", t1, t2, f)
Output:

true, true, false

func Split

func Split[TString ~string, TSep StringOrRune](s TString, seps ...TSep) []TString

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators. If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s. If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice. It is equivalent to SplitN with a count of -1. To split around the first instance of a separator, see Cut.

func SplitAfter

func SplitAfter[TString ~string, TSep StringOrRune](s TString, seps ...TSep) []TString

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings. If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s. If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice. It is equivalent to SplitAfterN with a count of -1.

func SplitAfterN

func SplitAfterN[TString ~string, TSep StringOrRune, TInt constraints.Integer](n TInt, s TString, seps ...TSep) []TString

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings. The count determines the number of substrings to return: n > 0: at most n substrings; the last substring will be the unsplit remainder. n == 0: the result is nil (zero substrings) n < 0: all substrings Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for SplitAfter.

func SplitN

func SplitN[TString ~string, TSep StringOrRune, TInt constraints.Integer](n TInt, s TString, seps ...TSep) []TString

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings. The count determines the number of substrings to return: n > 0: at most n substrings; the last substring will be the unsplit remainder. n == 0: the result is nil (zero substrings) n < 0: all substrings Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for SplitAfter.

func Title

func Title[TString ~string](s TString) TString

Title returns a string with English title casing. It uses an approximation of the default Unicode Word Break algorithm. If you want to have the title casing specific to another language, use TitleSpecial instead.

func TitleSpecial

func TitleSpecial[TString ~string](s TString, language language.Tag) TString

TitleSpecial returns a language-specific title casing of the given string. It uses an approximation of the default Unicode Word Break algorithm.

func ToBool

func ToBool[TString StringOrRune](s TString) (bool, error)

ToBool converts a string or rune to bool: "true", "t", or "1" case insensitive converts to true "false", "f", or "0" case insensitive converts to false.

Example
t1, err := ToBool("1")
if err != nil {
	panic(err)
}
t2, err := ToBool("t")
if err != nil {
	panic(err)
}
t3, err := ToBool("true")
if err != nil {
	panic(err)
}
t4, err := ToBool("True")
if err != nil {
	panic(err)
}

f1, err := ToBool("0")
if err != nil {
	panic(err)
}
f2, err := ToBool("f")
if err != nil {
	panic(err)
}
f3, err := ToBool("false")
if err != nil {
	panic(err)
}
f4, err := ToBool("False")
if err != nil {
	panic(err)
}

_, err = ToBool("junk")
if err == nil {
	panic("should have errored")
}

fmt.Printf("%t, %t, %t, %t | %t, %t, %t, %t", t1, t2, t3, t4, f1, f2, f3, f4)
Output:

true, true, true, true | false, false, false, false

func ToBoolOpt

func ToBoolOpt[TString StringOrRune](s TString) option.Option[bool]

ToBoolOpt converts a string or rune to an optional bool following the rules of ToBool. If the string will not convert to a bool, then it returns None.

Example
t1 := ToBoolOpt("1")
t2 := ToBoolOpt("t")
t3 := ToBoolOpt("true")
t4 := ToBoolOpt("True")
f1 := ToBoolOpt("0")
f2 := ToBoolOpt("f")
f3 := ToBoolOpt("false")
f4 := ToBoolOpt("False")

b := ToBoolOpt("junk")

fmt.Printf("%s, %s, %s, %s | %s, %s, %s, %s | %s", t1.String(), t2.String(), t3.String(), t4.String(), f1.String(), f2.String(), f3.String(), f4.String(), b.String())
Output:

Some(true), Some(true), Some(true), Some(true) | Some(false), Some(false), Some(false), Some(false) | None

func ToDate

func ToDate[TString ~string](s TString, format ...string) (time.Time, error)

ToDate accepts a date as a string, with an optional format to use in parsing it. If no format is supplied, it uses a predefined list and tries them until it finds one that succeeds. The predefined formats are only for dates. They do not parse times.

Example
d, err := ToDate("2022-3-14")
if err != nil {
	panic(err)
}
fmt.Printf("%v", d.Format(MDYYYYFullName))
Output:

March 14, 2022

func ToFloat

func ToFloat[TString StringOrRune](s TString) (float64, error)

ToFloat converts a string to a float64. If it fails, it returns a *NumError error from the strconv package.

Example
f1, err := ToFloat("123.4")
if err != nil {
	panic(err)
}
f2, err := ToFloat("5")
if err != nil {
	panic(err)
}
_, err = ToFloat("junk")
if err == nil {
	panic("should have errored")
}
fmt.Printf("%.2f, %.2f", f1, f2)
Output:

123.40, 5.00

func ToFloatOpt

func ToFloatOpt[TString StringOrRune](s TString) option.Option[float64]

ToFloatOpt converts from a string to to an optional float64 but on failure, returns None.

Example
f1 := ToFloatOpt("123.4")
f2 := ToFloatOpt("5")
b := ToFloatOpt("junk")

fmt.Printf("%.2f, %.2f, %s", f1.Value(), f2.Value(), b)
Output:

123.40, 5.00, None

func ToInt

func ToInt[TString StringOrRune](s TString) (int, error)

ToInt converts from a string to an integer.

Example
i1, err := ToInt("-1")
if err != nil {
	panic(err)
}
i2, err := ToInt("1025")
if err != nil {
	panic(err)
}
i3, err := ToInt8("127")
if err != nil {
	panic(err)
}
i4, err := ToInt8("128")
if err == nil {
	panic("should have error")
}

fmt.Printf("%d, %d, %d, %d", i1, i2, i3, i4)
Output:

-1, 1025, 127, 127

func ToInt16

func ToInt16[TString StringOrRune](s TString) (int16, error)

ToInt16 converts from a string to an integer.

func ToInt32

func ToInt32[TString StringOrRune](s TString) (int32, error)

ToInt32 converts from a string to an integer.

func ToInt64

func ToInt64[TString StringOrRune](s TString) (int64, error)

ToInt64 converts from a string to an integer.

func ToInt8

func ToInt8[TString StringOrRune](s TString) (int8, error)

ToInt8 converts from a string to an integer.

func ToIntOpt

func ToIntOpt[TString StringOrRune](s TString) option.Option[int]

ToIntOpt converts from a string to to an optional integer but on failure, returns None.

Example
i1 := ToIntOpt("-1")
i2 := ToIntOpt("junk")
fmt.Printf("%s, %s", i1, i2)
Output:

Some(-1), None

func ToStringSlice

func ToStringSlice[TString StringOrRune](input []TString) []string

ToStringSlice converts a slice of ~string or ~rune to a slice of string.

func ToValueUTF8

func ToValueUTF8[TString1, TString2 ~string](s TString1, replacement TString2) TString1

ToValidUTF8 returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.

func Trim

func Trim[TString1 ~string, TString2 StringOrRune](s TString1, cutset TString2) TString1

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

func TrimFunc

func TrimFunc[TString ~string, TRune ~rune](s TString, f func(TRune) bool) TString

TrimFunc returns a slice of the string s with all leading and trailing Unicode code points c satisfying f(c) removed.

func TrimLeft

func TrimLeft[TString1 ~string, TString2 StringOrRune](s TString1, cutset TString2) TString1

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed. To remove a prefix, use TrimPrefix instead.

func TrimLeftFunc

func TrimLeftFunc[TString ~string, TRune ~rune](s TString, f func(TRune) bool) TString

TrimLeftFunc returns a slice of the string s with all leading Unicode code points c satisfying f(c) removed.

func TrimPrefix

func TrimPrefix[TString1 ~string, TString2 StringOrRune](s TString1, prefix TString2) TString1

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

func TrimRight

func TrimRight[TString1 ~string, TString2 StringOrRune](s TString1, cutset TString2) TString1

TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed. To remove a suffix, use TrimSuffix instead.

func TrimRightFunc

func TrimRightFunc[TString ~string, TRune ~rune](s TString, f func(TRune) bool) TString

TrimRightFunc returns a slice of the string s with all trailing Unicode code points c satisfying f(c) removed.

func TrimSpace

func TrimSpace[TString1 ~string](s TString1) TString1

TrimSpace returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

func TrimSuffix

func TrimSuffix[TString1 ~string, TString2 StringOrRune](s TString1, suffix TString2) TString1

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

func Unquote

func Unquote[TString ~string](s TString) TString

Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal, returning the string value that s quotes. (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.)

func Upper

func Upper[TString ~string](s TString) TString

Upper returns a string with English upper casing. It uses an approximation of the default Unicode Word Break algorithm. If you want to have the upper casing specific to another language, use UpperSpecial instead.

func UpperSpecial

func UpperSpecial[TString ~string](s TString, language language.Tag) TString

UpperSpecial returns a string with language-specific upper casing of the given string. It uses an approximation of the default Unicode Word Break algorithm.

Types

type Builder

type Builder = strings.Builder

type Reader

type Reader = strings.Reader

type Replacer

type Replacer = strings.Replacer

func NewReplacer

func NewReplacer[TString StringOrRune](oldnew ...TString) *Replacer

NewReplacer returns a new Replacer from a list of old, new string pairs. Replacements are performed in the order they appear in the target string, without overlapping matches. The old string comparisons are done in argument order. NewReplacer panics if given an odd number of arguments.

type StringOrRune

type StringOrRune interface {
	~string | ~rune
}

StringOrRune is a type constraint that includes any type descended from string or from rune.

Jump to

Keyboard shortcuts

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