Documentation
¶
Overview ¶
Package strutil provides utility functions for string manipulation. This package includes various utility functions inspired by both the Go standard library and additional ideas from libraries like HuTool's StrUtil. It is designed to make common
Index ¶
- func Bytes(s string) []byte
- func Capitalize(s string) string
- func Concat(strs ...string) string
- func ConcatWithSeparator(strs []string, separator string) string
- func ContainsAny(s string, substrings []string) bool
- func CountOccurrences(s, substr string) int
- func DecodeBase64(s string) (string, error)
- func EncodeBase64(s string) string
- func Format(template string, args ...interface{}) string
- func HasBlank(s string) bool
- func HasEmpty(strs ...string) bool
- func HasNoBlank(s string) bool
- func HasNoEmpty(strs ...string) bool
- func IsBlank(s string) bool
- func IsEmpty(s string) bool
- func IsNumeric(s string) bool
- func JoinNonEmpty(strs []string, separator string) string
- func LevenshteinDistance(a, b string) int
- func NotBlank(s string) bool
- func NotEmpty(s string) bool
- func PadLeft(s string, length int, padChar rune) string
- func PadRight(s string, length int, padChar rune) string
- func Pluralize(word string, count int) string
- func RandomString(length int, charset string, secure ...bool) (string, error)
- func RegexReplace(s, pattern, replacement string) (string, error)
- func RemoveDuplicates(s string) string
- func RemoveNonAlphaNumeric(s string) string
- func RemovePrefix(s, prefix string) string
- func RemoveSuffix(s, suffix string) string
- func Reverse(s string) string
- func Slugify(s string) string
- func SplitAt(s string, index int) (string, string)
- func Str(b []byte) string
- func StripControlChars(s string) string
- func Sub(s string, start, length int) string
- func Substring(s string, start, end int) string
- func ToCamelCase(s string) string
- func ToLower(s string) string
- func ToSnakeCase(s string) string
- func ToUpper(s string) string
- func URLSafeDecodeBase64(s string) (string, error)
- func URLSafeEncodeBase64(s string) string
- func WordWrap(s string, width int) string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Bytes ¶
Bytes converts a string to a byte slice. This is a simple wrapper over []byte conversion.
Example usage: bytes := Bytes("Hello") bytes will be []byte{72, 101, 108, 108, 111}.
func Capitalize ¶
Capitalize optimizes the capitalization for ASCII strings. If the string contains only ASCII characters, it avoids converting to []rune.
Example usage: result := Capitalize("hello world") result will be "Hello world".
func Concat ¶
Concat concatenates multiple strings into a single string. It takes a variadic parameter of strings and efficiently appends them using a strings.Builder.
Example usage: result := Concat("Hello", " ", "World") result will be "Hello World".
func ConcatWithSeparator ¶
ConcatWithSeparator concatenates multiple strings with a specified separator. It uses strings.Join for simplicity and efficiency. If the input slice is empty, an empty string is returned.
Example usage: result := ConcatWithSeparator([]string{"Hello", "World"}, "-") result will be "Hello-World".
func ContainsAny ¶
ContainsAny checks if the input string contains any of the specified substrings. It returns true if any of the substrings are found.
Example usage: result := ContainsAny("hello world", []string{"earth", "world"}) result will be true.
func CountOccurrences ¶
CountOccurrences counts the number of occurrences of a specific substring in a given string. It repeatedly searches for the substring and adjusts the input string to start after each match.
Example usage: count := CountOccurrences("Hello World Hello", "Hello") count will be 2.
func DecodeBase64 ¶
DecodeBase64 decodes a Base64 encoded string. It returns the decoded string and an error if the input string is not valid Base64.
Example usage: decoded, err := DecodeBase64("SGVsbG8gV29ybGQ=") decoded will be "Hello World".
func EncodeBase64 ¶
EncodeBase64 encodes a string to Base64 format. It takes a string as input and returns the Base64 encoded representation of that string.
Example usage: encoded := EncodeBase64("Hello World") encoded will be "SGVsbG8gV29ybGQ=".
func Format ¶
Format replaces placeholders in a template string with provided arguments. Placeholders are denoted by "{}". The function replaces each occurrence of "{}" with the corresponding argument in the provided order.
Example usage: template := "{} loves {}" formatted := Format(template, "Alice", "Bob") formatted will be "Alice loves Bob".
func HasBlank ¶
HasBlank checks if a string contains any whitespace characters. It iterates over each rune in the string and returns true if any whitespace is found.
Example usage: hasBlank := HasBlank("Hello World") hasBlank will be true.
func HasEmpty ¶
HasEmpty checks if any of the provided strings are empty or nil. It returns true if any string in the variadic input is empty.
Example usage: hasEmpty := HasEmpty("Hello", "", "World") hasEmpty will be true.
func HasNoBlank ¶
HasNoBlank checks if a string contains no whitespace characters. It iterates over each rune in the string and returns true if no whitespace is found.
Example usage: hasNoBlank := HasNoBlank("HelloWorld") hasNoBlank will be true.
func HasNoEmpty ¶
HasNoEmpty checks if none of the provided strings are empty or nil. It returns true if no string in the variadic input is empty.
Example usage: hasNoEmpty := HasNoEmpty("Hello", "World") hasNoEmpty will be true.
func IsBlank ¶
IsBlank checks if a string is entirely composed of whitespace characters or is empty. It returns true if the string contains only whitespace or is empty.
Example usage: isBlank := IsBlank(" ") isBlank will be true.
func IsEmpty ¶
IsEmpty checks if a string is empty (length 0). It returns true if the string is empty.
Example usage: isEmpty := IsEmpty("") isEmpty will be true.
func IsNumeric ¶
IsNumeric checks if the input string consists only of numeric characters (0-9).
Example usage: result := IsNumeric("12345") result will be true.
func JoinNonEmpty ¶
JoinNonEmpty joins the non-empty strings in the slice with a specified separator. It skips over any empty strings.
Example usage: result := JoinNonEmpty([]string{"Hello", "", "World"}, " ") result will be "Hello World".
func LevenshteinDistance ¶
LevenshteinDistance calculates the Levenshtein distance between two strings, which represents the minimum number of single-character edits required to transform one string into the other.
Example usage: distance := LevenshteinDistance("kitten", "sitting") result will be 3.
func NotBlank ¶
NotBlank checks if a string is not entirely composed of whitespace characters. It returns true if the string contains any non-whitespace characters.
Example usage: notBlank := NotBlank("Hello") notBlank will be true.
func NotEmpty ¶
NotEmpty checks if a string is not empty (length > 0). It returns true if the string is not empty.
Example usage: notEmpty := NotEmpty("Hello") notEmpty will be true.
func PadLeft ¶
PadLeft pads the input string on the left with the specified padChar until it reaches the target length. If the string is already longer than or equal to the target length, it returns the original string.
Example usage: result := PadLeft("Go", 5, 'x') result will be "xxGo".
func PadRight ¶
PadRight pads the input string on the right with the specified padChar until it reaches the target length. If the string is already longer than or equal to the target length, it returns the original string.
Example usage: result := PadRight("Go", 5, 'x') result will be "Goxx".
func Pluralize ¶
Pluralize adds an "s" to the input string if the count is not 1. Useful for basic pluralization.
Example usage: result := Pluralize("apple", 2) result will be "apples".
func RandomString ¶
RandomString generates a random string of the specified length using characters from a given set. By default, it prioritizes performance using non-secure random generation (math/rand). If secure is true, it uses crypto/rand for cryptographically secure random numbers.
Parameters:
- length: The length of the random string to generate.
- charset: The set of characters to choose from for generating the random string.
- secure: A boolean indicating whether to use cryptographically secure random number generation. Defaults to false (non-secure, performance-first).
Returns: - A random string of the specified length. - An error if secure random generation fails (only applicable if secure is true).
func RegexReplace ¶
RegexReplace replaces all occurrences of a pattern in a string with a replacement string. It uses the regexp package for pattern matching and replacement.
Example usage: result := RegexReplace("Hello 123 World", "\\d+", "#") result will be "Hello # World".
func RemoveDuplicates ¶
RemoveDuplicates removes duplicate characters from the input string, leaving only the first occurrence of each. It returns the deduplicated string.
Example usage: result := RemoveDuplicates("aabbcc") result will be "abc".
func RemoveNonAlphaNumeric ¶
RemoveNonAlphaNumeric removes all non-alphanumeric characters from the input string.
Example usage: result := RemoveNonAlphaNumeric("a-b_c!d@e#f$g%h") result will be "abcdefgh".
func RemovePrefix ¶
RemovePrefix removes a specified prefix from a string, if it exists. If the prefix is not present, the original string is returned.
Example usage: result := RemovePrefix("HelloWorld", "Hello") result will be "World".
func RemoveSuffix ¶
RemoveSuffix removes a specified suffix from a string, if it exists. If the suffix is not present, the original string is returned.
Example usage: result := RemoveSuffix("HelloWorld", "World") result will be "Hello".
func Reverse ¶
Reverse reverses the order of characters in a string. It converts the string to a slice of runes to handle multi-byte characters correctly.
Example usage: reversed := Reverse("Hello") reversed will be "olleH".
func Slugify ¶
Slugify converts a string to a URL-friendly slug by removing non-alphanumeric characters and replacing spaces with hyphens.
Example usage: result := Slugify("Hello World!") result will be "hello-world".
func SplitAt ¶
SplitAt splits a string into two parts at the specified index.
Example usage: left, right := SplitAt("hello world", 5) left will be "hello", right will be " world".
func Str ¶
Str converts a byte slice to a string. This is a simple wrapper over string conversion.
Example usage: str := Str([]byte{72, 101, 108, 108, 111}) str will be "Hello".
func StripControlChars ¶
StripControlChars removes non-printable characters (control characters) from the input string.
Example usage: result := StripControlChars("Hello\x00World") result will be "HelloWorld".
func Sub ¶
Sub extracts a substring from the input string, supporting both ASCII and Unicode characters efficiently. The function handles negative start indices, which count from the end of the string, similar to Python. If the start index is negative, it is adjusted to refer to the correct position in the string. If the start or length parameters are out of range, an empty string is returned.
The function optimizes for ASCII strings by directly manipulating bytes when possible, and falls back to handling Unicode characters using runes (Unicode code points) when needed.
Parameters: - s: The input string from which to extract the substring. - start: The starting index of the substring. A negative value counts from the end of the string. - length: The length of the substring to extract.
Returns:
- A substring from the input string starting at 'start' and of 'length' characters. If the indices are invalid, it returns an empty string.
Example usage:
Sub("abcdefgh", 2, 3) // Returns "cde" Sub("abcdefgh", -3, 2) // Returns "fg"
func Substring ¶
Substring extracts a substring from a given string. The substring is defined by the start and end indices. The range is inclusive of the start index and exclusive of the end index. If the indices are out of bounds or invalid (e.g., start > end), an empty string is returned.
Example usage: substring := Substring("Hello World", 6, 11) substring will be "World".
func ToCamelCase ¶
ToCamelCase efficiently converts a snake_case or kebab-case string to camelCase. It skips unnecessary rune operations for ASCII strings. except the first one, and joins them together.
Example usage: result := ToCamelCase("hello_world") result will be "helloWorld".
func ToLower ¶
ToLower converts a string to lowercase. This function uses the standard library's strings.ToLower.
Example usage: result := ToLower("HELLO") result will be "hello".
func ToSnakeCase ¶
ToSnakeCase converts a camelCase string to snake_case. It identifies uppercase characters in the input string and inserts an underscore before each one. The resulting string is entirely in lowercase.
Example usage: result := ToSnakeCase("helloWorld") result will be "hello_world".
func ToUpper ¶
ToUpper converts a string to uppercase. This function uses the standard library's strings.ToUpper.
Example usage: result := ToUpper("hello") result will be "HELLO".
func URLSafeDecodeBase64 ¶
URLSafeDecodeBase64 decodes a URL-safe Base64 encoded string. It behaves similarly to DecodeBase64 but for URL-safe Base64 encoded strings.
Example usage: decoded, err := URLSafeDecodeBase64("SGVsbG8gV29ybGQ=") decoded will be "Hello World".
func URLSafeEncodeBase64 ¶
URLSafeEncodeBase64 encodes a string in URL-safe Base64 format. This ensures that the encoded string can be safely used in URLs, as it replaces characters like '+' and '/' with URL-safe alternatives.
Example usage: urlSafeEncoded := URLSafeEncodeBase64("Hello World") urlSafeEncoded will be "SGVsbG8gV29ybGQ=" (URL-safe version).
Types ¶
This section is empty.