stringutil

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2025 License: MIT Imports: 2 Imported by: 0

README

String Utilities

Overview

The String Utilities component provides additional string manipulation functions beyond what's available in the standard library. It offers case-insensitive operations, natural language formatting, whitespace handling, and other common string manipulation tasks that are frequently needed in applications.

Features

  • Case-Insensitive Operations: Perform prefix and substring checks without case sensitivity
  • Multiple Prefix Checking: Check if a string starts with any of multiple prefixes
  • Natural Language Formatting: Join strings with commas and "and" for human-readable output
  • Whitespace Handling: Check for empty strings and remove whitespace
  • String Truncation: Safely truncate strings with ellipsis
  • Path Normalization: Convert backslashes to forward slashes for cross-platform compatibility
  • UTF-8 Safe: All operations are safe for UTF-8 encoded strings
  • Zero Dependencies: No external dependencies beyond the Go standard library

Installation

go get github.com/abitofhelp/servicelib/stringutil

Quick Start

package main

import (
    "fmt"
    
    "github.com/abitofhelp/servicelib/stringutil"
)

func main() {
    // Case-insensitive operations
    fmt.Println(stringutil.HasPrefixIgnoreCase("Hello World", "hello"))  // true
    fmt.Println(stringutil.ContainsIgnoreCase("Hello World", "WORLD"))   // true
    
    // Join strings with natural language formatting
    items := []string{"apples", "bananas", "oranges"}
    fmt.Println(stringutil.JoinWithAnd(items, true))  // "apples, bananas, and oranges"
    
    // Check for empty strings
    fmt.Println(stringutil.IsEmpty("   "))  // true
    fmt.Println(stringutil.IsEmpty("Hello"))  // false
    
    // Truncate long strings
    longText := "This is a very long string that needs to be truncated"
    fmt.Println(stringutil.Truncate(longText, 20))  // "This is a very long..."
    
    // Normalize file paths
    path := "C:\\Users\\Username\\Documents"
    fmt.Println(stringutil.ForwardSlashPath(path))  // "C:/Users/Username/Documents"
}

API Documentation

Key Functions
HasPrefixIgnoreCase

Checks if a string begins with a prefix, ignoring case.

func HasPrefixIgnoreCase(s, prefix string) bool
ContainsIgnoreCase

Checks if a substring is within a string, ignoring case.

func ContainsIgnoreCase(s, substr string) bool
HasAnyPrefix

Checks if a string begins with any of the specified prefixes.

func HasAnyPrefix(s string, prefixes ...string) bool
ToLowerCase

Converts a string to lowercase.

func ToLowerCase(s string) string
JoinWithAnd

Joins a slice of strings with commas and "and".

func JoinWithAnd(items []string, useOxfordComma bool) string
IsEmpty

Checks if a string is empty or contains only whitespace.

func IsEmpty(s string) bool
IsNotEmpty

Checks if a string is not empty and contains non-whitespace characters.

func IsNotEmpty(s string) bool
Truncate

Truncates a string to a specified maximum length.

func Truncate(s string, maxLength int) string
RemoveWhitespace

Removes all whitespace characters from a string.

func RemoveWhitespace(s string) string
ForwardSlashPath

Converts backslashes in a path to forward slashes.

func ForwardSlashPath(path string) string

Examples

Currently, there are no dedicated examples for the stringutil package in the EXAMPLES directory. The following code snippets demonstrate common usage patterns:

Case-Insensitive String Operations
// Check if a string starts with a prefix, ignoring case
if stringutil.HasPrefixIgnoreCase(userInput, "cmd:") {
    // Process as a command
}

// Check if a string contains a substring, ignoring case
if stringutil.ContainsIgnoreCase(email, "@example.com") {
    // Handle example.com email addresses
}
Natural Language Formatting
// Join items with commas and "and"
selectedOptions := []string{"Option A", "Option B", "Option C"}
message := "You selected " + stringutil.JoinWithAnd(selectedOptions, true)
// "You selected Option A, Option B, and Option C"

// Without Oxford comma
message = "You selected " + stringutil.JoinWithAnd(selectedOptions, false)
// "You selected Option A, Option B and Option C"
String Validation and Manipulation
// Check if a string is empty or whitespace-only
if stringutil.IsEmpty(userInput) {
    return errors.New("input cannot be empty")
}

// Truncate a string for display
title := stringutil.Truncate(longArticleTitle, 50)

// Remove all whitespace
compactString := stringutil.RemoveWhitespace("  This   has   extra   spaces  ")
// "Thishasextraspaces"

Best Practices

  1. Use Case-Insensitive Functions When Appropriate: For user input and non-exact matching, use the case-insensitive functions
  2. Consider Oxford Comma Preference: When using JoinWithAnd, consider your audience's preference for Oxford commas
  3. Check for Empty Strings: Use IsEmpty instead of checking for "" to also catch whitespace-only strings
  4. Set Appropriate Truncation Lengths: When truncating strings, ensure the maxLength is appropriate for your display context
  5. Normalize Paths: Use ForwardSlashPath when working with file paths across different operating systems

Troubleshooting

Common Issues
Performance Considerations

If you're processing large volumes of strings:

  • Consider caching results of expensive operations
  • Be aware that regular expressions (used in RemoveWhitespace) can be slower for very large strings
  • For high-performance needs, consider using string builders for concatenation operations
Unicode Handling

All functions are UTF-8 safe, but be aware of potential issues:

  • Some operations may behave differently with non-ASCII characters
  • Length calculations are based on bytes, not characters, which can affect truncation of multi-byte characters
  • Validation - String validation utilities
  • Errors - Error handling that may use string formatting

Contributing

Contributions to this component are welcome! Please see the Contributing Guide for more information.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package stringutil provides additional string manipulation utilities beyond what's available in the standard library.

This package offers a collection of helper functions for common string operations that are not directly available in the standard library's strings package. It includes functions for case-insensitive comparisons, string joining with grammatical conventions, whitespace handling, and path normalization.

Key features:

  • Case-insensitive string operations (HasPrefixIgnoreCase, ContainsIgnoreCase)
  • Multiple prefix checking (HasAnyPrefix)
  • Grammatically correct string joining (JoinWithAnd)
  • Whitespace detection and removal (IsEmpty, IsNotEmpty, RemoveWhitespace)
  • String truncation with ellipsis (Truncate)
  • Path normalization (ForwardSlashPath)

Example usage:

// Case-insensitive prefix check
if stringutil.HasPrefixIgnoreCase(userInput, "help") {
    // Handle help command
}

// Join items with proper grammar
items := []string{"apples", "oranges", "bananas"}
fmt.Println("Shopping list: " + stringutil.JoinWithAnd(items, true))
// Output: "Shopping list: apples, oranges, and bananas"

// Normalize file paths
path := "C:\\Users\\username\\Documents"
normalizedPath := stringutil.ForwardSlashPath(path)
// Result: "C:/Users/username/Documents"

Package stringutil provides additional string manipulation utilities beyond what's available in the standard library.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContainsIgnoreCase

func ContainsIgnoreCase(s, substr string) bool

ContainsIgnoreCase checks if substr is within s, ignoring case. Both s and substr are converted to lowercase before comparison. Parameters:

  • s: The string to search in
  • substr: The substring to search for

Returns:

  • bool: true if substr is found in s (ignoring case), false otherwise

func ForwardSlashPath

func ForwardSlashPath(path string) string

ForwardSlashPath converts backslashes in a path to forward slashes. This is useful for normalizing file paths across different operating systems. Parameters:

  • path: The file path to normalize

Returns:

  • string: The path with all backslashes replaced by forward slashes

func HasAnyPrefix

func HasAnyPrefix(s string, prefixes ...string) bool

HasAnyPrefix checks if the string s begins with any of the specified prefixes. It iterates through the provided prefixes and returns as soon as a match is found. Parameters:

  • s: The string to check
  • prefixes: One or more prefixes to look for at the beginning of s

Returns:

  • bool: true if s starts with any of the prefixes, false otherwise

func HasPrefixIgnoreCase

func HasPrefixIgnoreCase(s, prefix string) bool

HasPrefixIgnoreCase checks if the string s begins with the specified prefix, ignoring case. It is safe for UTF-8 encoded strings and performs a case-insensitive comparison. Parameters:

  • s: The string to check
  • prefix: The prefix to look for at the beginning of s

Returns:

  • bool: true if s starts with prefix (ignoring case), false otherwise

func IsEmpty

func IsEmpty(s string) bool

IsEmpty checks if a string is empty or contains only whitespace. It uses strings.TrimSpace to remove all leading and trailing whitespace. Parameters:

  • s: The string to check

Returns:

  • bool: true if the string is empty or contains only whitespace, false otherwise

func IsNotEmpty

func IsNotEmpty(s string) bool

IsNotEmpty checks if a string is not empty and contains non-whitespace characters. It's the logical opposite of IsEmpty. Parameters:

  • s: The string to check

Returns:

  • bool: true if the string contains non-whitespace characters, false otherwise

func JoinWithAnd

func JoinWithAnd(items []string, useOxfordComma bool) string

JoinWithAnd joins a slice of strings with commas and "and". It handles different list lengths appropriately and supports Oxford comma usage. Parameters:

  • items: The slice of strings to join
  • useOxfordComma: Whether to include a comma before "and" for lists of 3 or more items

Returns:

  • string: The joined string, or an empty string if items is empty

func RemoveWhitespace

func RemoveWhitespace(s string) string

RemoveWhitespace removes all whitespace characters from a string. It uses a regular expression to match and remove spaces, tabs, newlines, and other whitespace. Parameters:

  • s: The string to process

Returns:

  • string: The string with all whitespace characters removed

func ToLowerCase

func ToLowerCase(s string) string

ToLowerCase converts a string to lowercase. It's a simple wrapper around strings.ToLower for consistency within the package. Parameters:

  • s: The string to convert to lowercase

Returns:

  • string: The lowercase version of the input string

func Truncate

func Truncate(s string, maxLength int) string

Truncate truncates a string to a specified maximum length. If the string is longer than maxLength, it adds "..." to the end. If maxLength is negative, it's treated as 0. Parameters:

  • s: The string to truncate
  • maxLength: The maximum length of the returned string before adding "..."

Returns:

  • string: The truncated string, or the original string if it's not longer than maxLength

Types

This section is empty.

Jump to

Keyboard shortcuts

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