strutil

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2024 License: MIT Imports: 8 Imported by: 0

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bytes

func Bytes(s string) []byte

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

func Capitalize(s string) string

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

func Concat(strs ...string) string

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

func ConcatWithSeparator(strs []string, separator string) string

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

func ContainsAny(s string, substrings []string) bool

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

func CountOccurrences(s, substr string) int

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

func DecodeBase64(s string) (string, error)

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

func EncodeBase64(s string) string

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

func Format(template string, args ...interface{}) string

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

func HasBlank(s string) bool

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

func HasEmpty(strs ...string) bool

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

func HasNoBlank(s string) bool

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

func HasNoEmpty(strs ...string) bool

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

func IsBlank(s string) bool

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

func IsEmpty(s string) bool

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

func IsNumeric(s string) bool

IsNumeric checks if the input string consists only of numeric characters (0-9).

Example usage: result := IsNumeric("12345") result will be true.

func JoinNonEmpty

func JoinNonEmpty(strs []string, separator string) string

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

func LevenshteinDistance(a, b string) int

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

func NotBlank(s string) bool

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

func NotEmpty(s string) bool

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

func PadLeft(s string, length int, padChar rune) string

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

func PadRight(s string, length int, padChar rune) string

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

func Pluralize(word string, count int) string

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

func RandomString(length int, charset string, secure ...bool) (string, error)

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

func RegexReplace(s, pattern, replacement string) (string, error)

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

func RemoveDuplicates(s string) string

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

func RemoveNonAlphaNumeric(s string) string

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

func RemovePrefix(s, prefix string) string

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

func RemoveSuffix(s, suffix string) string

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

func Reverse(s string) string

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

func Slugify(s string) string

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

func SplitAt(s string, index int) (string, string)

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

func Str(b []byte) string

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

func StripControlChars(s string) string

StripControlChars removes non-printable characters (control characters) from the input string.

Example usage: result := StripControlChars("Hello\x00World") result will be "HelloWorld".

func Sub

func Sub(s string, start, length int) string

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

func Substring(s string, start, end int) string

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

func ToCamelCase(s string) string

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

func ToLower(s string) string

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

func ToSnakeCase(s string) string

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

func ToUpper(s string) string

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

func URLSafeDecodeBase64(s string) (string, error)

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

func URLSafeEncodeBase64(s string) string

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).

func WordWrap

func WordWrap(s string, width int) string

WordWrap wraps a string into lines of a specified width, breaking at spaces when possible. If a word exceeds the width, it will be placed on a new line.

Example usage: result := WordWrap("This is a very long string", 10) result will be: "This is a very long string"

Types

This section is empty.

Jump to

Keyboard shortcuts

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