Documentation
¶
Overview ¶
Example (StringPointerBasic) ¶
Estos ejemplos ilustran cómo usar los punteros a strings para evitar asignaciones adicionales
// Creamos una variable string que queremos modificar myText := "héllô wórld" // En lugar de crear una nueva variable con el resultado, // modificamos directamente la variable original usando Apply() Convert(&myText).RemoveTilde().ToLower().Apply() // La variable original ha sido modificada fmt.Println(myText)
Output: hello world
Example (StringPointerCamelCase) ¶
// Ejemplo de uso con múltiples transformaciones originalText := "Él Múrcielago Rápido" // Las transformaciones modifican la variable original directamente // usando el método Apply() para actualizar el puntero Convert(&originalText).RemoveTilde().CamelCaseLower().Apply() fmt.Println(originalText)
Output: elMurcielagoRapido
Example (StringPointerEfficiency) ¶
// En aplicaciones de alto rendimiento, reducir asignaciones de memoria // puede ser importante para evitar la presión sobre el garbage collector // Método tradicional (crea nuevas asignaciones de memoria) traditionalText := "Texto con ACENTOS" processedText := Convert(traditionalText).RemoveTilde().ToLower().String() fmt.Println(processedText) // Método con punteros (modifica directamente la variable original) directText := "Otro TEXTO con ACENTOS" Convert(&directText).RemoveTilde().ToLower().Apply() fmt.Println(directText)
Output: texto con acentos otro texto con acentos
Index ¶
- func Contains(text, search string) bool
- func CountOccurrences(text, search string) int
- func ParseKeyValue(input string, delimiters ...string) (value string, err error)
- func Split(data string, separator ...string) (result []string)
- type Text
- func (t *Text) Apply()
- func (t *Text) CamelCaseLower() *Text
- func (t *Text) CamelCaseUpper() *Text
- func (t *Text) Capitalize() *Text
- func (t *Text) Down() *Text
- func (t *Text) FormatNumber() *Text
- func (t *Text) Join(sep ...string) *Text
- func (t *Text) Quote() *Text
- func (t *Text) RemoveTilde() *Text
- func (t *Text) Repeat(n int) *Text
- func (t *Text) Replace(oldAny, newAny any, n ...int) *Text
- func (t *Text) RoundDecimals(decimals int) *Text
- func (t *Text) String() string
- func (t *Text) StringError() (string, error)
- func (t *Text) ToBool() (bool, error)
- func (t *Text) ToFloat() (float64, error)
- func (t *Text) ToInt(base ...int) (int, error)
- func (t *Text) ToLower() *Text
- func (t *Text) ToSnakeCaseLower(sep ...string) *Text
- func (t *Text) ToSnakeCaseUpper(sep ...string) *Text
- func (t *Text) ToUint(base ...int) (uint, error)
- func (t *Text) ToUpper() *Text
- func (t *Text) Trim() *Text
- func (t *Text) TrimPrefix(prefix string) *Text
- func (t *Text) TrimSuffix(suffix string) *Text
- func (t *Text) Truncate(maxWidth any, reservedChars ...any) *Text
- func (t *Text) TruncateName(maxCharsPerWord, maxWidth any) *Text
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Contains ¶ added in v0.0.8
Contains checks if the string 'search' is present in 'text' Returns true if found, false otherwise This matches the behavior of the standard library strings.Contains
func CountOccurrences ¶ added in v0.0.8
CountOccurrences checks how many times the string 'search' is present in 'text' eg: "hello world" with search "world" will return 1
func ParseKeyValue ¶ added in v0.0.10
ParseKeyValue extracts the value part from a "key:value" formatted string. By default, it uses ":" as the delimiter but accepts an optional custom delimiter. The function returns the value part and an error (nil if successful).
Examples:
value, err := ParseKeyValue("name:John") // value = "John", err = nil value, err := ParseKeyValue("data=123", "=") // value = "123", err = nil value, err := ParseKeyValue("invalid-string") // value = "", err = error containing "delimiter ':' not found in string invalid-string"
Types ¶
type Text ¶
type Text struct {
// contains filtered or unexported fields
}
Text struct to store the content of the text - optimized for memory efficiency
func Convert ¶
Convert initializes a new Text struct with any type of value for string manipulation.
Supported input types:
- string: Direct string value
- *string: Pointer to string (allows in-place modification with Apply())
- []string: Slice of strings (use Join() to combine)
- int, int8, int16, int32, int64: Integer types
- uint, uint8, uint16, uint32, uint64: Unsigned integer types
- float32, float64: Floating point types
- bool: Boolean values (true/false)
- any other type: Converted to string representation
Usage patterns:
- Basic string manipulation: result := Convert("hello world").ToUpper().String() // result: "HELLO WORLD"
- In-place modification of string pointer: original := "hello world" Convert(&original).ToUpper().Apply() // original is now: "HELLO WORLD"
- Working with slices: words := []string{"hello", "world"} result := Convert(words).Join(" ").ToUpper().String() // result: "HELLO WORLD"
- Numeric conversions: result := Convert(42).String() // result: "42"
The Convert function returns a *Text instance that supports method chaining for various string transformations like case conversion, joining, parsing, etc. Use String() to get the final result or Apply() to modify the original pointer.
func Format ¶ added in v0.0.30
Format creates a new Text instance with variadic formatting similar to fmt.Sprintf Example: tinystring.Format("Hello %s, you have %d messages", "Alice", 5).String()
func FromFloat ¶ added in v0.0.30
FromFloat creates a new Text instance from a float64 with optional precision specification.
Parameters:
- value: The float64 value to convert to Text
- precision (optional): Number of decimal places to include. Default is -1 (full precision). Use 0 for no decimal places, positive values for fixed decimal places.
Returns:
- *Text: A new Text instance containing the string representation of the float
Usage examples:
// Full precision (default) text := FromFloat(123.456789) result := text.String() // "123.456789" (or full precision representation) // No decimal places text := FromFloat(123.456, 0) result := text.String() // "123" // Fixed decimal places text := FromFloat(123.456, 2) result := text.String() // "123.46" (rounded) // Scientific notation values text := FromFloat(1.23e-4, 6) result := text.String() // "0.000123" // Negative numbers text := FromFloat(-99.99, 1) result := text.String() // "-100.0" // Chain with other operations text := FromFloat(123.456, 2).ToUpper() result := text.String() // "123.46" (case conversion doesn't affect numbers)
Note: The precision parameter controls the number of digits after the decimal point. The resulting Text instance can be used for further string manipulations.
func FromInt ¶ added in v0.0.30
FromInt creates a new Text instance from an integer with optional base specification.
Parameters:
- value: The integer value to convert to Text
- base (optional): The numeric base for string representation (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)
Returns:
- *Text: A new Text instance containing the string representation of the integer
Usage examples:
// Basic decimal conversion text := FromInt(123) result := text.String() // "123" // Binary representation text := FromInt(10, 2) result := text.String() // "1010" // Hexadecimal representation text := FromInt(255, 16) result := text.String() // "ff" // Octal representation text := FromInt(64, 8) result := text.String() // "100" // Negative numbers (only base 10) text := FromInt(-42) result := text.String() // "-42"
Note: The resulting Text instance can be used for further string manipulations like case conversion, joining, etc.
func FromUint ¶ added in v0.0.30
FromUint creates a new Text instance from an unsigned integer with optional base specification.
Parameters:
- value: The unsigned integer value to convert to Text
- base (optional): The numeric base for string representation (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)
Returns:
- *Text: A new Text instance containing the string representation of the unsigned integer
Usage examples:
// Basic decimal conversion text := FromUint(123) result := text.String() // "123" // Binary representation text := FromUint(10, 2) result := text.String() // "1010" // Hexadecimal representation text := FromUint(255, 16) result := text.String() // "ff" // Large unsigned values text := FromUint(18446744073709551615) // max uint64 result := text.String() // "18446744073709551615" // Chain with other operations text := FromUint(255, 16).ToUpper() result := text.String() // "FF"
Note: Unlike FromInt, this function only works with non-negative values. The resulting Text instance can be used for further string manipulations.
func (*Text) Apply ¶ added in v0.0.28
func (t *Text) Apply()
Apply updates the original string pointer with the current content. This method should be used when you want to modify the original string directly without additional allocations.
func (*Text) CamelCaseLower ¶
converts text to camelCase (first word lowercase) eg: "Hello world" -> "helloWorld"
func (*Text) CamelCaseUpper ¶
converts text to PascalCase (all words capitalized) eg: "hello world" -> "HelloWorld"
func (*Text) Capitalize ¶ added in v0.0.11
Capitalize transforms the first letter of each word to uppercase and the rest to lowercase. For example: "hello world" -> "Hello World"
func (*Text) Down ¶ added in v0.0.30
Down applies downward rounding to a previously rounded number This method works by taking the current rounded value and ensuring it represents the floor Example: Convert(3.154).RoundDecimals(2).Down().String() → "3.15"
func (*Text) FormatNumber ¶ added in v0.0.17
FormatNumber formats a numeric value with thousand separators Example: Convert(1234567).FormatNumber().String() → "1,234,567"
func (*Text) Join ¶ added in v0.0.24
Join concatenates the elements of a string slice to create a single string. If no separator is provided, it uses a space as default. Can be called with varargs to specify a custom separator. eg: Convert([]string{"Hello", "World"}).Join() => "Hello World" eg: Convert([]string{"Hello", "World"}).Join("-") => "Hello-World"
func (*Text) Quote ¶ added in v0.0.30
Quote wraps a string in double quotes and escapes any special characters Example: Quote("hello \"world\"") returns "\"hello \\\"world\\\"\""
func (*Text) Repeat ¶ added in v0.0.13
Repeat returns the string s repeated n times. If n is less than or equal to zero, or if s is empty, it returns an empty string. eg: Convert("abc").Repeat(3) => "abcabcabc"
func (*Text) Replace ¶ added in v0.0.7
Replace replaces up to n occurrences of old with new in the text content If n < 0, there is no limit on the number of replacements eg: "hello world" with old "world" and new "universe" will return "hello universe" Old and new can be any type, they will be converted to string using anyToString
func (*Text) RoundDecimals ¶ added in v0.0.17
RoundDecimals rounds a numeric value to the specified number of decimal places Default behavior is rounding up. Use .Down() to round down. Example: Convert(3.154).RoundDecimals(2).String() → "3.16"
func (*Text) String ¶
String method to return the content of the text without modifying any original pointers
func (*Text) StringError ¶ added in v0.0.30
StringError returns the content of the text along with any error that occurred during processing
func (*Text) ToBool ¶ added in v0.0.30
ToBool converts the text content to a boolean value Returns the boolean value and any error that occurred
func (*Text) ToFloat ¶ added in v0.0.30
ToFloat converts the text content to a float64 (double precision floating point).
Returns:
- float64: The converted floating point value
- error: Any error that occurred during conversion
Conversion behavior:
- Parses the string content as a floating point number
- Supports both positive and negative numbers
- Handles decimal points and scientific notation (if implemented)
- Returns error for invalid number formats
Supported input formats:
- Integer strings: "123" -> 123.0, "-456" -> -456.0
- Decimal numbers: "123.45", "-99.99", "0.001"
- Numbers with leading signs: "+123.45", "-0.99"
- Zero values: "0", "0.0", "0.000"
Usage examples:
// Basic decimal conversion val, err := Convert("123.45").ToFloat() // val: 123.45, err: nil // Integer to float val, err := Convert("42").ToFloat() // val: 42.0, err: nil // Negative numbers val, err := Convert("-99.99").ToFloat() // val: -99.99, err: nil // Error handling val, err := Convert("invalid").ToFloat() // val: 0.0, err: conversion error
Note: This method uses a custom float parsing implementation that may have different precision characteristics compared to the standard library.
func (*Text) ToInt ¶ added in v0.0.30
ToInt converts the text content to an integer with optional base specification.
Parameters:
- base (optional): The numeric base for conversion (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)
Returns:
- int: The converted integer value
- error: Any error that occurred during conversion
Conversion behavior:
- First attempts direct integer parsing with the specified base
- If that fails, tries to parse as float and truncates to integer
- Returns error if both methods fail
Supported input formats:
- Integer strings: "123", "-456"
- Float strings (truncated): "123.45" -> 123, "99.99" -> 99
- Different bases: "1010" (base 2) -> 10, "FF" (base 16) -> 255
- Negative numbers: Only supported for base 10
Usage examples:
// Basic decimal conversion val, err := Convert("123").ToInt() // val: 123, err: nil // Binary conversion val, err := Convert("1010").ToInt(2) // val: 10, err: nil // Hexadecimal conversion val, err := Convert("FF").ToInt(16) // val: 255, err: nil // Float truncation val, err := Convert("123.99").ToInt() // val: 123, err: nil // Error handling val, err := Convert("invalid").ToInt() // val: 0, err: conversion error
Note: Negative numbers are only supported for base 10. For other bases, negative signs will result in an error.
func (*Text) ToSnakeCaseLower ¶
snakeCase converts a string to snake_case format with optional separator. If no separator is provided, underscore "_" is used as default. Example:
Input: "camelCase" -> Output: "camel_case" Input: "PascalCase", "-" -> Output: "pascal-case" Input: "APIResponse" -> Output: "api_response" Input: "user123Name", "." -> Output: "user123.name"
ToSnakeCaseLower converts text to snake_case format
func (*Text) ToSnakeCaseUpper ¶
ToSnakeCaseUpper converts text to Snake_Case format
func (*Text) ToUint ¶ added in v0.0.30
ToUint converts the text content to an unsigned integer with optional base specification.
Parameters:
- base (optional): The numeric base for conversion (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)
Returns:
- uint: The converted unsigned integer value
- error: Any error that occurred during conversion
Conversion behavior:
- First attempts direct unsigned integer parsing with the specified base
- If that fails, tries to parse as float and truncates to unsigned integer
- Returns error if both methods fail or if the value is negative
Supported input formats:
- Positive integer strings: "123", "456"
- Float strings (truncated): "123.45" -> 123, "99.99" -> 99
- Different bases: "1010" (base 2) -> 10, "FF" (base 16) -> 255
- Negative numbers: NOT supported, will return error
Usage examples:
// Basic decimal conversion val, err := Convert("123").ToUint() // val: 123, err: nil // Binary conversion val, err := Convert("1010").ToUint(2) // val: 10, err: nil // Hexadecimal conversion val, err := Convert("FF").ToUint(16) // val: 255, err: nil // Float truncation val, err := Convert("123.99").ToUint() // val: 123, err: nil // Error with negative number val, err := Convert("-123").ToUint() // val: 0, err: "negative numbers are not supported for unsigned integers"
Note: Negative numbers are never supported for unsigned integers and will always result in an error, regardless of the base.
func (*Text) Trim ¶ added in v0.0.7
Trim removes spaces at the beginning and end of the text content eg: " hello world " will return "hello world"
func (*Text) TrimPrefix ¶ added in v0.0.9
TrimPrefix removes the specified prefix from the text content if it exists eg: "prefix-hello" with prefix "prefix-" will return "hello"
func (*Text) TrimSuffix ¶ added in v0.0.7
TrimSuffix removes the specified suffix from the text content if it exists eg: "hello.txt" with suffix ".txt" will return "hello"
func (*Text) Truncate ¶ added in v0.0.13
Truncate truncates a text so that it does not exceed the specified width. If the text is longer, it truncates it and adds "..." if there is space. If the text is shorter or equal to the width, it remains unchanged. The reservedChars parameter indicates how many characters should be reserved for suffixes. This parameter is optional - if not provided, no characters are reserved (equivalent to passing 0). eg: Convert("Hello, World!").Truncate(10) => "Hello, ..." eg: Convert("Hello, World!").Truncate(10, 3) => "Hell..." eg: Convert("Hello").Truncate(10) => "Hello"
func (*Text) TruncateName ¶ added in v0.0.20
TruncateName truncates names and surnames in a user-friendly way for display in limited spaces like chart labels. It adds abbreviation dots where appropriate. This method processes the first word differently if there are more than 2 words in the text.
Parameters:
- maxCharsPerWord: maximum number of characters to keep per word (any numeric type)
- maxWidth: maximum total length for the final string (any numeric type)
Examples:
- Convert("Jeronimo Dominguez").TruncateName(3, 15) => "Jer. Dominguez"
- Convert("Ana Maria Rodriguez").TruncateName(2, 10) => "An. Mar..."
- Convert("Juan").TruncateName(3, 5) => "Juan"