stringx

package
v0.0.0-...-6e5fdd9 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2025 License: AGPL-3.0 Imports: 7 Imported by: 6

README

stringx - Advanced String Manipulation Utilities

The stringx package provides high-performance string manipulation utilities with zero-copy optimizations, Unicode support, and advanced string processing functions. It extends Go's standard strings package with additional functionality for common string operations.

Features

  • Zero-Copy Conversions: Efficient string/byte slice conversions using unsafe operations
  • Case Conversions: Camel case, snake case, kebab case, and other case conversions
  • String Generation: Random string generation with customizable character sets
  • Unicode Support: Full Unicode support for text processing
  • Performance Optimized: Memory-efficient operations with minimal allocations
  • Validation Functions: String validation and checking utilities
  • Text Processing: Advanced text manipulation and formatting functions

Installation

go get github.com/lazygophers/utils/stringx

Usage Examples

Zero-Copy String/Byte Conversions
package main

import (
    "fmt"
    "github.com/lazygophers/utils/stringx"
)

func main() {
    // Zero-copy string to bytes conversion
    str := "hello world"
    bytes := stringx.ToBytes(str)
    fmt.Printf("String: %s, Bytes: %v\n", str, bytes)

    // Zero-copy bytes to string conversion
    data := []byte("hello world")
    result := stringx.ToString(data)
    fmt.Printf("Bytes: %v, String: %s\n", data, result)
}
Case Conversions
// Camel case to snake case
camelCase := "getUserProfile"
snakeCase := stringx.Camel2Snake(camelCase)
fmt.Println(snakeCase) // get_user_profile

// Snake case to camel case
snakeStr := "user_profile_data"
camelStr := stringx.Snake2Camel(snakeStr)
fmt.Println(camelStr) // userProfileData

// Kebab case conversions
kebabCase := stringx.Camel2Kebab("getUserProfile")
fmt.Println(kebabCase) // get-user-profile

// Pascal case conversions
pascalCase := stringx.Snake2Pascal("user_profile")
fmt.Println(pascalCase) // UserProfile
Random String Generation
// Generate random string with default charset (alphanumeric)
randomStr := stringx.RandString(10)
fmt.Println(randomStr) // e.g., "Kj8mNq2Lp9"

// Generate random string with custom charset
customStr := stringx.RandStringWithCharset(8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
fmt.Println(customStr) // e.g., "MXKQWERT"

// Generate random alphanumeric string
alphaNum := stringx.RandAlphaNumeric(12)
fmt.Println(alphaNum) // e.g., "Abc123Def456"

// Generate random alphabetic string
alpha := stringx.RandAlphabetic(6)
fmt.Println(alpha) // e.g., "XyZabc"

// Generate random numeric string
numeric := stringx.RandNumeric(4)
fmt.Println(numeric) // e.g., "1234"
String Validation and Checking
// Check if string is alphanumeric
isAlphaNum := stringx.IsAlphaNumeric("Abc123")
fmt.Println(isAlphaNum) // true

// Check if string is alphabetic only
isAlpha := stringx.IsAlphabetic("HelloWorld")
fmt.Println(isAlpha) // true

// Check if string is numeric only
isNumeric := stringx.IsNumeric("12345")
fmt.Println(isNumeric) // true

// Check if string is ASCII
isASCII := stringx.IsASCII("Hello World")
fmt.Println(isASCII) // true

// Check if string is empty or whitespace
isEmpty := stringx.IsBlank("   ")
fmt.Println(isEmpty) // true
Text Processing
// Reverse string
reversed := stringx.Reverse("hello")
fmt.Println(reversed) // "olleh"

// Capitalize first letter
capitalized := stringx.Capitalize("hello world")
fmt.Println(capitalized) // "Hello world"

// Title case
title := stringx.ToTitle("hello world")
fmt.Println(title) // "Hello World"

// Center string with padding
centered := stringx.Center("hello", 10, " ")
fmt.Println(centered) // "  hello   "

// Truncate string with ellipsis
truncated := stringx.Truncate("This is a long string", 10)
fmt.Println(truncated) // "This is..."

// Remove duplicates from string
noDupes := stringx.RemoveDuplicates("hello")
fmt.Println(noDupes) // "helo"
Advanced String Operations
// Split string and trim spaces
parts := stringx.SplitAndTrim("apple, banana, cherry", ",")
fmt.Println(parts) // ["apple", "banana", "cherry"]

// Join non-empty strings
joined := stringx.JoinNonEmpty([]string{"hello", "", "world", ""}, " ")
fmt.Println(joined) // "hello world"

// Extract words from string
words := stringx.ExtractWords("Hello, World! How are you?")
fmt.Println(words) // ["Hello", "World", "How", "are", "you"]

// Count occurrences of substring
count := stringx.CountOccurrences("hello world hello", "hello")
fmt.Println(count) // 2

// Replace multiple substrings
replacements := map[string]string{"hello": "hi", "world": "earth"}
replaced := stringx.ReplaceMultiple("hello world", replacements)
fmt.Println(replaced) // "hi earth"

API Reference

Zero-Copy Conversions
  • ToString(b []byte) string - Convert byte slice to string (zero-copy)
  • ToBytes(s string) []byte - Convert string to byte slice (zero-copy)
Case Conversions
  • Camel2Snake(s string) string - Convert camelCase to snake_case
  • Snake2Camel(s string) string - Convert snake_case to camelCase
  • Camel2Kebab(s string) string - Convert camelCase to kebab-case
  • Snake2Pascal(s string) string - Convert snake_case to PascalCase
  • Pascal2Snake(s string) string - Convert PascalCase to snake_case
  • Kebab2Camel(s string) string - Convert kebab-case to camelCase
Random String Generation
  • RandString(length int) string - Generate random alphanumeric string
  • RandStringWithCharset(length int, charset string) string - Generate with custom charset
  • RandAlphaNumeric(length int) string - Generate alphanumeric string
  • RandAlphabetic(length int) string - Generate alphabetic string
  • RandNumeric(length int) string - Generate numeric string
  • RandHex(length int) string - Generate hexadecimal string
  • RandBase64(length int) string - Generate base64 string
String Validation
  • IsAlphaNumeric(s string) bool - Check if string is alphanumeric
  • IsAlphabetic(s string) bool - Check if string is alphabetic
  • IsNumeric(s string) bool - Check if string is numeric
  • IsASCII(s string) bool - Check if string contains only ASCII characters
  • IsBlank(s string) bool - Check if string is empty or whitespace
  • IsEmpty(s string) bool - Check if string is empty
  • IsUpper(s string) bool - Check if string is uppercase
  • IsLower(s string) bool - Check if string is lowercase
Text Processing
  • Reverse(s string) string - Reverse string
  • Capitalize(s string) string - Capitalize first letter
  • ToTitle(s string) string - Convert to title case
  • Center(s string, width int, fillChar string) string - Center with padding
  • PadLeft(s string, width int, padChar string) string - Left pad
  • PadRight(s string, width int, padChar string) string - Right pad
  • Truncate(s string, length int) string - Truncate with ellipsis
  • TruncateWords(s string, wordCount int) string - Truncate by word count
Advanced Operations
  • SplitAndTrim(s, sep string) []string - Split and trim whitespace
  • JoinNonEmpty(strs []string, sep string) string - Join non-empty strings
  • ExtractWords(s string) []string - Extract words from text
  • CountOccurrences(s, substr string) int - Count substring occurrences
  • ReplaceMultiple(s string, replacements map[string]string) string - Multiple replacements
  • RemoveDuplicates(s string) string - Remove duplicate characters
  • Similarity(s1, s2 string) float64 - Calculate string similarity
Unicode Support
  • ContainsUnicode(s string) bool - Check if string contains Unicode
  • UnicodeLength(s string) int - Get Unicode character count
  • UnicodeSubstring(s string, start, length int) string - Unicode-aware substring
  • NormalizeSpaces(s string) string - Normalize whitespace characters

Performance Characteristics

The package is optimized for high performance:

Zero-Copy Operations
// These operations don't allocate new memory
bytes := stringx.ToBytes("hello")    // O(1), no allocation
str := stringx.ToString([]byte{...}) // O(1), no allocation
Optimized Case Conversions
  • ASCII-only strings use optimized fast path
  • Unicode strings use efficient buffering
  • Pre-calculated capacity to minimize reallocations
Memory-Efficient Random Generation
  • Reuses character sets and buffers
  • Minimal allocations for repeated calls

Best Practices

  1. Use Zero-Copy Functions: Use ToString() and ToBytes() for efficient conversions
  2. Choose Appropriate Functions: Use specific validation functions instead of regex
  3. Pre-allocate for Bulk Operations: When processing many strings, consider pre-allocation
  4. Handle Unicode Properly: Use Unicode-aware functions for international text
  5. Validate Input: Always validate string input in public APIs

Examples

Configuration Key Conversion
// Convert configuration keys between formats
configKeys := []string{
    "database_host",
    "database_port",
    "api_timeout",
    "log_level",
}

// Convert to environment variable format
for _, key := range configKeys {
    envKey := strings.ToUpper(key)
    fmt.Printf("%s -> %s\n", key, envKey)
}

// Convert to camelCase for JSON
for _, key := range configKeys {
    jsonKey := stringx.Snake2Camel(key)
    fmt.Printf("%s -> %s\n", key, jsonKey)
}
Text Processing Pipeline
// Process user input text
userInput := "  Hello, WORLD!  How are YOU today?  "

// Clean and normalize
cleaned := strings.TrimSpace(userInput)
normalized := stringx.NormalizeSpaces(cleaned)
title := stringx.ToTitle(normalized)

fmt.Println(title) // "Hello, World! How Are You Today?"

// Extract and analyze words
words := stringx.ExtractWords(normalized)
fmt.Printf("Word count: %d\n", len(words))
ID and Token Generation
// Generate various types of identifiers
sessionID := stringx.RandHex(32)
apiKey := stringx.RandBase64(24)
userToken := stringx.RandAlphaNumeric(16)

fmt.Printf("Session ID: %s\n", sessionID)
fmt.Printf("API Key: %s\n", apiKey)
fmt.Printf("User Token: %s\n", userToken)
  • candy - Type conversion utilities
  • validator - String validation utilities
  • json - JSON string processing

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllControl

func AllControl(s string) bool

func AllDigit

func AllDigit(s string) bool

func AllGraphic

func AllGraphic(s string) bool

func AllLetter

func AllLetter(s string) bool

func AllLetterOrDigit

func AllLetterOrDigit(s string) bool

func AllLower

func AllLower(s string) bool

func AllMark

func AllMark(s string) bool

func AllPrint

func AllPrint(s string) bool

func AllPunct

func AllPunct(s string) bool

func AllSpace

func AllSpace(s string) bool

func AllSymbol

func AllSymbol(s string) bool

func AllTitle

func AllTitle(s string) bool

func AllUpper

func AllUpper(s string) bool

func Camel2Snake

func Camel2Snake(s string) string

Camel2Snake 驼峰转蛇形 - 内存优化版本

func ContainsAny

func ContainsAny(s, chars string) bool

ContainsAny reports whether any of the UTF-8-encoded code points in chars are within s.

func ContainsRune

func ContainsRune(s string, r rune) bool

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

func Count

func Count(s, substr string) int

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

func EqualFold

func EqualFold(s, t string) bool

EqualFold reports whether s and t are equal under Unicode case-folding.

func Fields

func Fields(s string) []string

Fields splits the string s around each instance of one or more consecutive white space characters.

func FieldsFunc

func FieldsFunc(s string, f func(rune) bool) []string

FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c).

func HasControl

func HasControl(s string) bool

func HasDigit

func HasDigit(s string) bool

func HasGraphic

func HasGraphic(s string) bool

func HasLetter

func HasLetter(s string) bool

func HasLetterOrDigit

func HasLetterOrDigit(s string) bool

func HasLower

func HasLower(s string) bool

func HasMark

func HasMark(s string) bool

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix tests whether the string s begins with prefix.

func HasPrint

func HasPrint(s string) bool

func HasPunct

func HasPunct(s string) bool

func HasSpace

func HasSpace(s string) bool

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix tests whether the string s ends with suffix.

func HasSymbol

func HasSymbol(s string) bool

func HasTitle

func HasTitle(s string) bool

func HasUpper

func HasUpper(s string) bool

func Index

func Index(s, substr string) 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(s, chars string) 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 IsDigit

func IsDigit[M string | []rune](r M) bool

func IsUpper

func IsUpper[M string | []rune](r M) bool

func LastIndex

func LastIndex(s, substr string) 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(s, chars string) int

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

func Quote

func Quote(s string) string

func QuotePure

func QuotePure(s string) string

func RandLetterNumbers

func RandLetterNumbers(n int) string

func RandLetters

func RandLetters(n int) string

func RandLowerLetterNumbers

func RandLowerLetterNumbers(n int) string

func RandLowerLetters

func RandLowerLetters(n int) string

func RandNumbers

func RandNumbers(n int) string

func RandStringWithSeed

func RandStringWithSeed(n int, seed []rune) string

func RandUpperLetterNumbers

func RandUpperLetterNumbers(n int) string

func RandUpperLetters

func RandUpperLetters(n int) string

func Repeat

func Repeat(s string, count int) string

Repeat returns a new string consisting of count copies of the string s.

func Replace

func Replace(s, old, new string, n int) string

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new.

func ReplaceAll

func ReplaceAll(s, old, new string) string

ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new.

func Reverse

func Reverse(s string) string

func Shorten

func Shorten(s string, max int) string

Shorten 缩短字符串

func ShortenShow

func ShortenShow(s string, max int) string

func Snake2Camel

func Snake2Camel(s string) string

Snake2Camel 蛇形转驼峰

func Snake2SmallCamel

func Snake2SmallCamel(s string) string

Snake2SmallCamel 蛇形转小驼峰

func Split

func Split(s, sep string) []string

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

func SplitAfter

func SplitAfter(s, sep string) []string

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.

func SplitAfterN

func SplitAfterN(s, sep string, n int) []string

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings.

func SplitLen

func SplitLen(s string, max int) []string

SplitLen 按长度分割字符串 - 零拷贝优化版本

func SplitN

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

SplitN slices s into substrings separated by sep and returns a slice of the substrings between those separators.

func Title

func Title(s string) string

Title returns a copy of the string s with all Unicode letters that begin words mapped to their Unicode title case.

func ToBytes

func ToBytes(s string) []byte

func ToCamel

func ToCamel(s string) string

ToCamel 转驼峰

func ToDot

func ToDot(s string) string

func ToKebab

func ToKebab(s string) string

ToKebab - 基于优化ToSnake的变体

func ToLower

func ToLower(s string) string

ToLower returns s with all Unicode letters mapped to their lower case.

func ToSlash

func ToSlash(s string) string

func ToSmallCamel

func ToSmallCamel(s string) string

ToSmallCamel 转小驼峰

func ToSnake

func ToSnake(s string) string

ToSnake 蛇形 - 零分配优化版本

func ToString

func ToString(b []byte) string

func ToTitle

func ToTitle(s string) string

ToTitle returns a copy of the string s with all Unicode letters mapped to their Unicode title case.

func ToUpper

func ToUpper(s string) string

ToUpper returns s with all Unicode letters mapped to their upper case.

func Trim

func Trim(s, cutset string) string

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

func TrimLeft

func TrimLeft(s, cutset string) string

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

func TrimPrefix

func TrimPrefix(s, prefix string) string

TrimPrefix returns s without the provided leading prefix string.

func TrimRight

func TrimRight(s, cutset string) string

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

func TrimSpace

func TrimSpace(s string) string

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

func TrimSuffix

func TrimSuffix(s, suffix string) string

TrimSuffix returns s without the provided trailing suffix string.

func Utf16Len

func Utf16Len[M string | []rune | []byte](str M) int

Types

This section is empty.

Jump to

Keyboard shortcuts

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