stringutil

package
v0.0.0-...-14a125a Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2025 License: MIT Imports: 11 Imported by: 0

README

Stringutil Package / 문자열 유틸리티 패키지

Go Version License

Extreme simplicity string utility functions for Go. Reduces 10-20 lines of repetitive code to a single function call.

Go를 위한 극도로 간단한 문자열 유틸리티 함수. 10-20줄의 반복 코드를 단일 함수 호출로 줄입니다.

Design Philosophy / 설계 철학: "20 lines → 1 line"

Features / 기능

108+ utility functions across 13 categories / 13개 카테고리에 걸쳐 108개 이상 유틸리티 함수

🚀 Minimal dependencies - standard library + golang.org/x/text / 최소 의존성

🌍 Unicode-safe - works with 한글, 日本語, emoji 🎉 / 유니코드 안전

📝 Bilingual docs - English/Korean / 이중 언어 문서

🎯 Comprehensive - string manipulation, validation, case conversion, Unicode operations, Builder pattern, encoding, distance algorithms, formatting / 포괄적

🔗 Fluent API - Builder pattern with 30+ chainable methods / 30개 이상의 체이닝 가능한 메서드를 가진 Builder 패턴

Installation / 설치

go get github.com/arkd0ng/go-utils/stringutil

Quick Start / 빠른 시작

import "github.com/arkd0ng/go-utils/stringutil"

// Builder pattern - fluent API / Builder 패턴 - 유창한 API
result := stringutil.NewBuilder().
    Append("  user profile data  ").
    Clean().
    ToSnakeCase().
    Truncate(15).
    Build()  // "user_profile_da..."

// Case conversion / 케이스 변환
stringutil.ToSnakeCase("UserProfileData")  // "user_profile_data"
stringutil.ToCamelCase("user-profile-data") // "userProfileData"
stringutil.ToTitle("hello world")           // "Hello World"
stringutil.Slugify("Hello World!")          // "hello-world"

// String manipulation / 문자열 조작
stringutil.Truncate("Hello World", 8)      // "Hello..."
stringutil.Clean("  hello   world  ")      // "hello world"
stringutil.Substring("hello world", 0, 5)  // "hello"
stringutil.Insert("hello world", 5, ",")   // "hello, world"
stringutil.SwapCase("Hello World")         // "hELLO wORLD"

// Encoding/Decoding / 인코딩/디코딩
stringutil.Base64Encode("hello")           // "aGVsbG8="
stringutil.URLEncode("hello world")        // "hello+world"
stringutil.HTMLEscape("<script>")          // "&lt;script&gt;"

// Distance & Similarity / 거리 및 유사도
stringutil.LevenshteinDistance("kitten", "sitting")  // 3
stringutil.Similarity("hello", "hallo")              // 0.8

// Formatting / 포맷팅
stringutil.FormatNumber(1000000, ",")      // "1,000,000"
stringutil.FormatBytes(1536)               // "1.5 KB"
stringutil.MaskEmail("[email protected]") // "j******[email protected]"

// Validation / 유효성 검사
stringutil.IsEmail("[email protected]")     // true
stringutil.IsURL("https://example.com")    // true

// Comparison / 비교
stringutil.EqualFold("hello", "HELLO")     // true
stringutil.HasPrefix("hello world", "hello") // true

// Unicode operations / 유니코드 작업
stringutil.RuneCount("안녕하세요")          // 5 (not 15 bytes)
stringutil.Width("hello世界")               // 9 (5 + 4)
stringutil.Normalize("café", "NFC")        // "café" (composed)

API Categories / API 카테고리

1. Case Conversion / 케이스 변환 (9 functions)
Function Input Output
ToSnakeCase "UserProfileData" "user_profile_data"
ToCamelCase "user_profile_data" "userProfileData"
ToKebabCase "UserProfileData" "user-profile-data"
ToPascalCase "user_profile_data" "UserProfileData"
ToScreamingSnakeCase "userProfileData" "USER_PROFILE_DATA"
ToTitle "hello world" "Hello World"
Slugify "Hello World!" "hello-world"
Quote "hello" "\"hello\""
Unquote "\"hello\"" "hello"
2. String Manipulation / 문자열 조작 (17 functions)
  • Truncate(s string, length int) string - Truncates with "..."
  • TruncateWithSuffix(s string, length int, suffix string) string - Custom suffix
  • Reverse(s string) string - Reverses string (Unicode-safe)
  • Capitalize(s string) string - Capitalizes each word
  • CapitalizeFirst(s string) string - Capitalizes first letter only
  • RemoveDuplicates(s string) string - Removes duplicate characters
  • RemoveSpaces(s string) string - Removes all whitespace
  • RemoveSpecialChars(s string) string - Keeps only alphanumeric
  • Clean(s string) string - Trims and deduplicates spaces
  • Repeat(s string, count int) string - Repeats string count times
  • Substring(s string, start, end int) string - Extracts substring (Unicode-safe)
  • Left(s string, n int) string - Gets leftmost n characters
  • Right(s string, n int) string - Gets rightmost n characters
  • Insert(s string, index int, insert string) string - Inserts at index
  • SwapCase(s string) string - Swaps upper/lowercase
3. Validation / 유효성 검사 (8 functions)
  • IsEmail(s string) bool - Email format (practical, not RFC 5322)
  • IsURL(s string) bool - URL with http:// or https://
  • IsAlphanumeric(s string) bool - Only a-z, A-Z, 0-9
  • IsNumeric(s string) bool - Only 0-9
  • IsAlpha(s string) bool - Only a-z, A-Z
  • IsBlank(s string) bool - Empty or whitespace only
  • IsLower(s string) bool - All lowercase letters
  • IsUpper(s string) bool - All uppercase letters
4. Comparison / 비교 (3 functions)
  • EqualFold(s1, s2 string) bool - Case-insensitive comparison
  • HasPrefix(s, prefix string) bool - Check string prefix
  • HasSuffix(s, suffix string) bool - Check string suffix
5. Search & Replace / 검색 및 치환 (6 functions)
  • ContainsAny(s string, substrs []string) bool
  • ContainsAll(s string, substrs []string) bool
  • StartsWithAny(s string, prefixes []string) bool
  • EndsWithAny(s string, suffixes []string) bool
  • ReplaceAll(s string, replacements map[string]string) string
  • ReplaceIgnoreCase(s, old, new string) string
6. Unicode Operations / 유니코드 작업 (3 functions)
  • RuneCount(s string) int - Count Unicode characters (not bytes)
  • Width(s string) int - Calculate display width (CJK double-width support)
  • Normalize(s string, form string) string - Unicode normalization (NFC/NFD/NFKC/NFKD)
7. String Generation / 문자열 생성 (2 functions)
  • PadLeft(s string, length int, pad string) string
  • PadRight(s string, length int, pad string) string
8. String Parsing / 문자열 파싱 (2 functions)
  • Lines(s string) []string
  • Words(s string) []string
9. Collection Utilities / 컬렉션 유틸리티 (5 functions)
  • CountWords(s string) int
  • CountOccurrences(s, substr string) int
  • Join(strs []string, sep string) string
  • Map(strs []string, fn func(string) string) []string
  • Filter(strs []string, fn func(string) bool) []string
10. Builder Pattern / Builder 패턴 (30+ methods)

Fluent API for chaining string operations / 문자열 작업을 체이닝하기 위한 유창한 API

// Basic usage / 기본 사용법
builder := stringutil.NewBuilder()
result := builder.Append("hello").ToUpper().Build()  // "HELLO"

// Complex chaining / 복잡한 체이닝
result := stringutil.NewBuilder().
    Append("  user profile data  ").
    Clean().
    ToSnakeCase().
    Truncate(15).
    Build()  // "user_profile_da..."

Available methods / 사용 가능한 메서드:

  • Construction: NewBuilder(), NewBuilderWithString(s)
  • Case conversion: ToSnakeCase(), ToCamelCase(), ToKebabCase(), ToPascalCase(), ToTitle(), ToUpper(), ToLower()
  • Manipulation: Append(s), AppendLine(s), Capitalize(), Reverse(), Trim(), Clean(), RemoveSpaces(), RemoveSpecialChars()
  • Truncation: Truncate(length), TruncateWithSuffix(length, suffix)
  • Formatting: Slugify(), Quote(), Unquote(), PadLeft(length, pad), PadRight(length, pad)
  • Transformation: Replace(old, new), Repeat(count)
  • Utility: Build(), String(), Len(), Reset()
11. Encoding & Decoding / 인코딩 및 디코딩 (8 functions)
  • Base64Encode(s string) string - Standard Base64 encoding
  • Base64Decode(s string) (string, error) - Standard Base64 decoding
  • Base64URLEncode(s string) string - URL-safe Base64 encoding
  • Base64URLDecode(s string) (string, error) - URL-safe Base64 decoding
  • URLEncode(s string) string - URL query string encoding
  • URLDecode(s string) (string, error) - URL query string decoding
  • HTMLEscape(s string) string - HTML entity escaping
  • HTMLUnescape(s string) string - HTML entity unescaping
12. Distance & Similarity / 거리 및 유사도 (4 functions)
  • LevenshteinDistance(a, b string) int - Edit distance (insertions, deletions, substitutions)
  • Similarity(a, b string) float64 - Similarity score (0.0-1.0) based on Levenshtein
  • HammingDistance(a, b string) int - Count of differing positions (equal-length strings)
  • JaroWinklerSimilarity(a, b string) float64 - Jaro-Winkler similarity (0.0-1.0)

Use cases / 사용 사례:

  • Fuzzy search / 퍼지 검색
  • Typo correction / 오타 수정
  • Duplicate detection / 중복 감지
  • String matching / 문자열 매칭
13. Formatting / 포맷팅 (13 functions)
  • FormatNumber(n int, separator string) string - Format numbers with thousand separators
  • FormatBytes(bytes int64) string - Human-readable byte sizes (KB, MB, GB, etc.)
  • Pluralize(count int, singular, plural string) string - Singular/plural based on count
  • FormatWithCount(count int, singular, plural string) string - Count with pluralized noun
  • Ellipsis(s string, maxLen int) string - Truncate with ellipsis in middle
  • Mask(s string, first, last int, maskChar string) string - Mask middle characters
  • MaskEmail(email string) string - Mask email (show first/last + domain)
  • MaskCreditCard(card string) string - Mask credit card (show last 4 digits)
  • AddLineNumbers(s string) string - Add line numbers to text
  • Indent(s string, prefix string) string - Indent each line with prefix
  • Dedent(s string) string - Remove common leading whitespace
  • WrapText(s string, width int) string - Wrap text to specified width

Examples / 예제

See examples/stringutil for complete examples.

완전한 예제는 examples/stringutil을 참조하세요.

Testing / 테스팅

go test ./stringutil -v

License / 라이선스

MIT License - see LICENSE file

Contributing / 기여

Contributions are welcome! Please see CONTRIBUTING.md

기여를 환영합니다! CONTRIBUTING.md를 참조하세요.

Documentation

Overview

Package stringutil provides extreme simplicity string utility functions. stringutil 패키지는 극도로 간단한 문자열 유틸리티 함수를 제공합니다.

This package reduces 10-20 lines of repetitive string manipulation code to a single function call. All functions are Unicode-safe and have no external dependencies (standard library only).

이 패키지는 10-20줄의 반복적인 문자열 조작 코드를 단일 함수 호출로 줄입니다. 모든 함수는 유니코드 안전하며 외부 의존성이 없습니다 (표준 라이브러리만).

Design Philosophy: "20 lines → 1 line" 설계 철학: "20줄 → 1줄"

Categories: - Case Conversion: ToSnakeCase, ToCamelCase, ToKebabCase, ToPascalCase - String Manipulation: Truncate, Reverse, Capitalize, Clean - Validation: IsEmail, IsURL, IsAlphanumeric, IsNumeric - Search & Replace: ContainsAny, ContainsAll, ReplaceAll - Utilities: CountWords, PadLeft, Lines, Words

Example:

import "github.com/arkd0ng/go-utils/stringutil"

// Case conversion 케이스 변환

stringutil.ToSnakeCase("UserProfileData")  // "user_profile_data"
stringutil.ToCamelCase("user-profile-data") // "userProfileData"

// String manipulation 문자열 조작

stringutil.Truncate("Hello World", 8)      // "Hello..."
stringutil.Clean("  hello   world  ")      // "hello world"

// Validation 유효성 검사

stringutil.IsEmail("[email protected]")     // true
stringutil.IsURL("https://example.com")    // true

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddLineNumbers

func AddLineNumbers(s string) string

AddLineNumbers adds line numbers to each line of text. AddLineNumbers는 텍스트의 각 줄에 줄 번호를 추가합니다.

Example 예제:

AddLineNumbers("line1\nline2\nline3")
// "1: line1\n2: line2\n3: line3"

func Base64Decode

func Base64Decode(s string) (string, error)

Base64Decode decodes a base64 string. Base64Decode는 base64 문자열을 디코딩합니다.

Returns an error if the input is not valid base64. 입력이 유효한 base64가 아니면 에러를 반환합니다.

Example 예제:

Base64Decode("aGVsbG8=")  // "hello", nil
Base64Decode("invalid!")  // "", error

func Base64Encode

func Base64Encode(s string) string

Base64Encode encodes a string to base64. Base64Encode는 문자열을 base64로 인코딩합니다.

Example 예제:

Base64Encode("hello")  // "aGVsbG8="

func Base64URLDecode

func Base64URLDecode(s string) (string, error)

Base64URLDecode decodes a URL-safe base64 string. Base64URLDecode는 URL 안전 base64 문자열을 디코딩합니다.

Returns an error if the input is not valid URL-safe base64. 입력이 유효한 URL 안전 base64가 아니면 에러를 반환합니다.

Example 예제:

Base64URLDecode("aGVsbG8_d29ybGQ=")  // "hello?world", nil

func Base64URLEncode

func Base64URLEncode(s string) string

Base64URLEncode encodes a string to URL-safe base64. Base64URLEncode는 문자열을 URL 안전 base64로 인코딩합니다.

URL-safe base64 uses '-' and '_' instead of '+' and '/'. URL 안전 base64는 '+'와 '/' 대신 '-'와 '_'를 사용합니다.

Example 예제:

Base64URLEncode("hello?world")  // "aGVsbG8_d29ybGQ="

func Capitalize

func Capitalize(s string) string

Capitalize capitalizes the first letter of each word. Capitalize는 각 단어의 첫 글자를 대문자로 만듭니다.

Example:

Capitalize("hello world")  // "Hello World"
Capitalize("hello-world")  // "Hello-World"

func CapitalizeFirst

func CapitalizeFirst(s string) string

CapitalizeFirst capitalizes only the first letter of the string. CapitalizeFirst는 문자열의 첫 글자만 대문자로 만듭니다.

Example:

CapitalizeFirst("hello world")  // "Hello world"
CapitalizeFirst("HELLO WORLD")  // "HELLO WORLD"

func Clean

func Clean(s string) string

Clean trims whitespace and deduplicates spaces. Clean은 공백을 제거하고 중복 공백을 정리합니다.

Example:

Clean("  hello   world  ")  // "hello world"
Clean("\t\nhello\t\nworld")  // "hello world"

func ContainsAll

func ContainsAll(s string, substrs []string) bool

ContainsAll returns true if the string contains all of the substrings. ContainsAll은 문자열이 모든 부분 문자열을 포함하면 true를 반환합니다.

Example:

ContainsAll("hello world", []string{"hello", "world"})  // true
ContainsAll("hello world", []string{"hello", "foo"})    // false

func ContainsAny

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

ContainsAny returns true if the string contains any of the substrings. ContainsAny는 문자열이 부분 문자열 중 하나라도 포함하면 true를 반환합니다.

Example:

ContainsAny("hello world", []string{"foo", "world"})  // true
ContainsAny("hello world", []string{"foo", "bar"})    // false

func CountOccurrences

func CountOccurrences(s, substr string) int

CountOccurrences counts the number of times a substring appears in a string. CountOccurrences는 부분 문자열이 문자열에 나타나는 횟수를 셉니다.

Example:

CountOccurrences("hello hello", "hello")  // 2
CountOccurrences("abcabc", "abc")          // 2

func CountWords

func CountWords(s string) int

CountWords counts the number of words in a string (split by whitespace). CountWords는 문자열의 단어 수를 셉니다 (공백으로 분리).

Example:

CountWords("hello world")  // 2
CountWords("  a  b  c  ")  // 3

func Dedent

func Dedent(s string) string

Dedent removes common leading whitespace from each line. Dedent는 각 줄에서 공통 선행 공백을 제거합니다.

Example 예제:

Dedent("  line1\n  line2")  // "line1\nline2"
Dedent("    line1\n  line2")  // "  line1\nline2"

func Ellipsis

func Ellipsis(s string, maxLen int) string

Ellipsis truncates a string and adds ellipsis in the middle. Ellipsis는 문자열을 자르고 중간에 ellipsis를 추가합니다.

If maxLen is less than or equal to 3, just truncates without ellipsis. maxLen이 3 이하이면 ellipsis 없이 자릅니다.

Example 예제:

Ellipsis("verylongfilename.txt", 15)  // "verylo...me.txt"
Ellipsis("short.txt", 20)             // "short.txt"
Ellipsis("abcdefgh", 3)               // "abc"

func EndsWithAny

func EndsWithAny(s string, suffixes []string) bool

EndsWithAny returns true if the string ends with any of the suffixes. EndsWithAny는 문자열이 접미사 중 하나로 끝나면 true를 반환합니다.

Example:

EndsWithAny("file.txt", []string{".txt", ".md"})  // true
EndsWithAny("file.jpg", []string{".txt", ".md"})  // false

func EqualFold

func EqualFold(s1, s2 string) bool

EqualFold compares two strings case-insensitively. EqualFold는 두 문자열을 대소문자 구분 없이 비교합니다.

Returns true if strings are equal ignoring case. 대소문자를 무시하고 문자열이 같으면 true를 반환합니다.

Example:

EqualFold("hello", "HELLO")  // true
EqualFold("GoLang", "golang") // true
EqualFold("hello", "world")  // false

func Filter

func Filter(strs []string, fn func(string) bool) []string

Filter filters strings by a predicate function. Filter는 조건 함수로 문자열을 필터링합니다.

Example:

Filter([]string{"a", "ab", "abc"}, func(s string) bool { return len(s) > 2 })  // ["abc"]
Filter([]string{"hello", "world", "hi"}, func(s string) bool { return len(s) > 3 })  // ["hello", "world"]

func FormatBytes

func FormatBytes(bytes int64) string

FormatBytes formats bytes as human-readable size (KB, MB, GB, etc.). FormatBytes는 바이트를 사람이 읽을 수 있는 크기로 포맷합니다 (KB, MB, GB 등).

Example 예제:

FormatBytes(1024)                 // "1.0 KB"
FormatBytes(1536)                 // "1.5 KB"
FormatBytes(1048576)              // "1.0 MB"
FormatBytes(1073741824)           // "1.0 GB"
FormatBytes(1099511627776)        // "1.0 TB"

func FormatNumber

func FormatNumber(n int, separator string) string

FormatNumber formats an integer with thousand separators. FormatNumber는 천 단위 구분 기호로 정수를 포맷합니다.

Example 예제:

FormatNumber(1000000, ",")     // "1,000,000"
FormatNumber(1234567, ".")     // "1.234.567"
FormatNumber(1234567, " ")     // "1 234 567"
FormatNumber(123, ",")         // "123"

func FormatWithCount

func FormatWithCount(count int, singular, plural string) string

FormatWithCount returns a formatted string with count and pluralized noun. FormatWithCount는 count와 복수형 명사를 포함한 포맷된 문자열을 반환합니다.

Example 예제:

FormatWithCount(1, "item", "items")    // "1 item"
FormatWithCount(5, "item", "items")    // "5 items"
FormatWithCount(0, "item", "items")    // "0 items"

func HTMLEscape

func HTMLEscape(s string) string

HTMLEscape escapes special HTML characters. HTMLEscape는 특수 HTML 문자를 이스케이프합니다.

Escapes: <, >, &, ", ' 이스케이프: <, >, &, ", '

Example 예제:

HTMLEscape("<div>hello</div>")  // "&lt;div&gt;hello&lt;/div&gt;"
HTMLEscape("'hello' & \"world\"")  // "&#39;hello&#39; &amp; &#34;world&#34;"

func HTMLUnescape

func HTMLUnescape(s string) string

HTMLUnescape unescapes HTML entities. HTMLUnescape는 HTML 엔티티를 언이스케이프합니다.

Example 예제:

HTMLUnescape("&lt;div&gt;hello&lt;/div&gt;")  // "<div>hello</div>"
HTMLUnescape("&#39;hello&#39; &amp; &#34;world&#34;")  // "'hello' & \"world\""

func HammingDistance

func HammingDistance(a, b string) int

HammingDistance calculates the Hamming distance between two strings of equal length. HammingDistance는 같은 길이의 두 문자열 사이의 Hamming 거리를 계산합니다.

The Hamming distance is the number of positions at which the corresponding characters are different. Hamming 거리는 해당 문자가 다른 위치의 수입니다.

Returns -1 if strings have different lengths. 문자열 길이가 다르면 -1을 반환합니다.

Example 예제:

HammingDistance("karolin", "kathrin")  // 3
HammingDistance("hello", "hello")      // 0
HammingDistance("hello", "world")      // 4
HammingDistance("hello", "hi")         // -1 (different lengths)

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix checks if string starts with the given prefix. HasPrefix는 문자열이 주어진 접두사로 시작하는지 확인합니다.

Example:

HasPrefix("hello world", "hello")  // true
HasPrefix("golang", "go")          // true
HasPrefix("hello", "world")        // false

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix checks if string ends with the given suffix. HasSuffix는 문자열이 주어진 접미사로 끝나는지 확인합니다.

Example:

HasSuffix("hello world", "world")  // true
HasSuffix("golang", "lang")        // true
HasSuffix("hello", "world")        // false

func Indent

func Indent(s string, prefix string) string

Indent indents each line with the specified prefix. Indent는 각 줄을 지정된 접두사로 들여쓰기합니다.

Example 예제:

Indent("line1\nline2", "  ")  // "  line1\n  line2"
Indent("line1\nline2", "\t")  // "\tline1\n\tline2"

func Insert

func Insert(s string, index int, insert string) string

Insert inserts a string at the specified index (Unicode-safe). Insert는 지정된 인덱스에 문자열을 삽입합니다 (유니코드 안전).

If index is negative or greater than length, it's adjusted to valid range. 인덱스가 음수이거나 길이보다 크면 유효한 범위로 조정됩니다.

Example:

Insert("hello world", 5, ",")    // "hello, world"

Insert("hello", 0, "say ") // "say hello" Insert("안녕하세요", 2, " 반갑습니다 ") // "안녕 반갑습니다 하세요"

func IsAlpha

func IsAlpha(s string) bool

IsAlpha checks if string contains only letters (a-z, A-Z). IsAlpha는 문자열이 알파벳만 포함하는지 확인합니다 (a-z, A-Z).

Example:

IsAlpha("abcABC")  // true
IsAlpha("hello")   // true
IsAlpha("abc123")  // false (has digits)
IsAlpha("abc-")    // false (has dash)

func IsAlphanumeric

func IsAlphanumeric(s string) bool

IsAlphanumeric checks if string contains only alphanumeric characters (a-z, A-Z, 0-9). IsAlphanumeric은 문자열이 영숫자만 포함하는지 확인합니다 (a-z, A-Z, 0-9).

Example:

IsAlphanumeric("abc123")   // true
IsAlphanumeric("ABC")      // true
IsAlphanumeric("abc-123")  // false (has dash)
IsAlphanumeric("abc 123")  // false (has space)

func IsBlank

func IsBlank(s string) bool

IsBlank checks if string is empty or contains only whitespace. IsBlank는 문자열이 비어있거나 공백만 포함하는지 확인합니다.

Example:

IsBlank("")       // true
IsBlank("   ")    // true
IsBlank("\t\n")   // true
IsBlank("hello")  // false
IsBlank(" a ")    // false

func IsEmail

func IsEmail(s string) bool

IsEmail validates if a string is an email address (practical validation). IsEmail은 문자열이 이메일 주소인지 검증합니다 (실용적 검증).

Not RFC 5322 compliant, but good enough for 99% of cases. RFC 5322 완전 준수 아니지만 99%의 경우에 충분함.

Example:

IsEmail("[email protected]")      // true
IsEmail("[email protected]")  // true
IsEmail("invalid.email")         // false
IsEmail("@example.com")          // false

func IsLower

func IsLower(s string) bool

IsLower checks if all letters in string are lowercase. IsLower는 문자열의 모든 글자가 소문자인지 확인합니다.

Example:

IsLower("hello")   // true
IsLower("abc")     // true
IsLower("Hello")   // false
IsLower("ABC")     // false
IsLower("abc123")  // true (digits don't affect)

func IsNumeric

func IsNumeric(s string) bool

IsNumeric checks if string contains only digits (0-9). IsNumeric은 문자열이 숫자만 포함하는지 확인합니다 (0-9).

Example:

IsNumeric("12345")   // true
IsNumeric("0")       // true
IsNumeric("123.45")  // false (has dot)
IsNumeric("-123")    // false (has minus)

func IsURL

func IsURL(s string) bool

IsURL validates if a string is a URL. IsURL은 문자열이 URL인지 검증합니다.

Checks for http:// or https:// scheme. http:// 또는 https:// 스킴 확인.

Example:

IsURL("https://example.com")       // true
IsURL("http://example.com/path")   // true
IsURL("example.com")               // false (no scheme)
IsURL("htp://invalid")             // false

func IsUpper

func IsUpper(s string) bool

IsUpper checks if all letters in string are uppercase. IsUpper는 문자열의 모든 글자가 대문자인지 확인합니다.

Example:

IsUpper("HELLO")   // true
IsUpper("ABC")     // true
IsUpper("Hello")   // false
IsUpper("abc")     // false
IsUpper("ABC123")  // true (digits don't affect)

func JaroWinklerSimilarity

func JaroWinklerSimilarity(a, b string) float64

JaroWinklerSimilarity calculates the Jaro-Winkler similarity between two strings (0.0 to 1.0). JaroWinklerSimilarity는 두 문자열 사이의 Jaro-Winkler 유사도를 계산합니다 (0.0 ~ 1.0).

The Jaro-Winkler similarity is a variant of the Jaro similarity metric with extra weight given to common prefixes.

Jaro-Winkler 유사도는 공통 접두사에 추가 가중치를 부여하는 Jaro 유사도 메트릭의 변형입니다.

Example 예제:

JaroWinklerSimilarity("martha", "marhta")  // 0.961
JaroWinklerSimilarity("hello", "hello")    // 1.0
JaroWinklerSimilarity("hello", "world")    // 0.466

func Join

func Join(strs []string, sep string) string

Join joins a slice of strings with a separator (wrapper for strings.Join). Join은 구분자로 문자열 슬라이스를 연결합니다 (strings.Join의 래퍼).

Example:

Join([]string{"a", "b", "c"}, "-")  // "a-b-c"
Join([]string{"hello", "world"}, " ")  // "hello world"

func Left

func Left(s string, n int) string

Left returns the leftmost n characters of a string (Unicode-safe). Left는 문자열의 가장 왼쪽 n개 문자를 반환합니다 (유니코드 안전).

If n is greater than string length, returns the entire string. n이 문자열 길이보다 크면 전체 문자열을 반환합니다.

Example:

Left("hello world", 5) // "hello" Left("안녕하세요", 2) // "안녕"

Left("hello", 10)       // "hello"

func LevenshteinDistance

func LevenshteinDistance(a, b string) int

LevenshteinDistance calculates the Levenshtein distance between two strings. LevenshteinDistance는 두 문자열 사이의 Levenshtein 거리를 계산합니다.

The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into another.

Levenshtein 거리는 한 문자열을 다른 문자열로 변경하는 데 필요한 최소 단일 문자 편집(삽입, 삭제 또는 치환) 횟수입니다.

Example 예제:

LevenshteinDistance("kitten", "sitting")  // 3
LevenshteinDistance("hello", "hello")     // 0
LevenshteinDistance("", "hello")          // 5

func Lines

func Lines(s string) []string

Lines splits a string by newlines. Lines는 줄바꿈으로 문자열을 분리합니다.

Example:

Lines("line1\nline2\nline3")  // ["line1", "line2", "line3"]
Lines("a\nb\nc")               // ["a", "b", "c"]

func Map

func Map(strs []string, fn func(string) string) []string

Map applies a function to all strings in a slice. Map은 슬라이스의 모든 문자열에 함수를 적용합니다.

Example:

Map([]string{"a", "b"}, strings.ToUpper)  // ["A", "B"]
Map([]string{"hello", "world"}, func(s string) string { return s + "!" })  // ["hello!", "world!"]

func Mask

func Mask(s string, first, last int, maskChar string) string

Mask masks a string with a character, revealing only first and last n characters. Mask는 문자열을 문자로 마스크하고, 처음과 마지막 n개 문자만 표시합니다.

If first+last is greater than or equal to string length, returns original string. first+last가 문자열 길이보다 크거나 같으면 원본 문자열을 반환합니다.

Example 예제:

Mask("1234567890", 2, 2, "*")      // "12******90"
Mask("[email protected]", 2, 4, "*")  // "he*****.com"
Mask("secret", 1, 1, "#")          // "s####t"
Mask("short", 2, 2, "*")           // "short"

func MaskCreditCard

func MaskCreditCard(card string) string

MaskCreditCard masks a credit card number, revealing only the last 4 digits. MaskCreditCard는 신용카드 번호를 마스크하고, 마지막 4자리만 표시합니다.

Example 예제:

MaskCreditCard("1234567890123456")  // "************3456"
MaskCreditCard("1234-5678-9012-3456")  // "****-****-****-3456"

func MaskEmail

func MaskEmail(email string) string

MaskEmail masks an email address, revealing only the first character and domain. MaskEmail은 이메일 주소를 마스크하고, 첫 문자와 도메인만 표시합니다.

Example 예제:

MaskEmail("[email protected]")  // "j******[email protected]"
MaskEmail("[email protected]")         // "[email protected]"

func Normalize

func Normalize(s string, form string) string

Normalize normalizes a Unicode string to the specified form. Normalize는 유니코드 문자열을 지정된 형식으로 정규화합니다.

Normalization Form: 정규화 형식:

  • "NFC": Canonical Decomposition followed by Canonical Composition
  • "NFD": Canonical Decomposition
  • "NFKC": Compatibility Decomposition followed by Canonical Composition
  • "NFKD": Compatibility Decomposition

Default is NFC if form is empty or invalid. form이 비어있거나 유효하지 않으면 기본값은 NFC입니다.

Example:

Normalize("café", "NFC")   // "café" (composed é)
Normalize("café", "NFD")   // "café" (decomposed e + ́)
Normalize("①②③", "NFKC")  // "123" (compatibility)

func PadLeft

func PadLeft(s string, length int, pad string) string

PadLeft pads a string on the left side to reach the specified length. PadLeft는 지정된 길이에 도달하도록 문자열의 왼쪽에 패딩을 추가합니다.

Example:

PadLeft("5", 3, "0")    // "005"
PadLeft("42", 5, "0")   // "00042"

func PadRight

func PadRight(s string, length int, pad string) string

PadRight pads a string on the right side to reach the specified length. PadRight는 지정된 길이에 도달하도록 문자열의 오른쪽에 패딩을 추가합니다.

Example:

PadRight("5", 3, "0")   // "500"
PadRight("42", 5, "0")  // "42000"

func Pluralize

func Pluralize(count int, singular, plural string) string

Pluralize returns the singular or plural form based on count. Pluralize는 count에 따라 단수형 또는 복수형을 반환합니다.

Example 예제:

Pluralize(1, "item", "items")      // "item"
Pluralize(5, "item", "items")      // "items"
Pluralize(0, "item", "items")      // "items"
Pluralize(1, "person", "people")   // "person"
Pluralize(5, "person", "people")   // "people"

func Quote

func Quote(s string) string

Quote wraps a string in double quotes and escapes internal quotes. Quote는 문자열을 큰따옴표로 감싸고 내부 따옴표를 이스케이프합니다.

Example:

Quote("hello")       // "\"hello\""
Quote("say \"hi\"")  // "\"say \\\"hi\\\"\""

func RemoveDuplicates

func RemoveDuplicates(s string) string

RemoveDuplicates removes duplicate characters from a string. RemoveDuplicates는 문자열에서 중복 문자를 제거합니다.

Example:

RemoveDuplicates("hello")  // "helo"
RemoveDuplicates("aabbcc")  // "abc"

func RemoveSpaces

func RemoveSpaces(s string) string

RemoveSpaces removes all whitespace from a string. RemoveSpaces는 문자열에서 모든 공백을 제거합니다.

Example:

RemoveSpaces("h e l l o")  // "hello"
RemoveSpaces("  hello world  ")  // "helloworld"

func RemoveSpecialChars

func RemoveSpecialChars(s string) string

RemoveSpecialChars removes special characters, keeping only alphanumeric and spaces. RemoveSpecialChars는 특수 문자를 제거하고 영숫자와 공백만 유지합니다.

Example:

RemoveSpecialChars("hello@#$123")  // "hello123"
RemoveSpecialChars("a!b@c#123")    // "abc123"

func Repeat

func Repeat(s string, count int) string

Repeat repeats a string n times. Repeat는 문자열을 n번 반복합니다.

Unicode-safe: works correctly with all Unicode characters. 유니코드 안전: 모든 유니코드 문자와 정상 작동.

Example:

Repeat("hello", 3) // "hellohellohello" Repeat("안녕", 2) // "안녕안녕"

Repeat("*", 5)      // "*****"

func ReplaceAll

func ReplaceAll(s string, replacements map[string]string) string

ReplaceAll replaces multiple strings at once using a replacement map. ReplaceAll은 치환 맵을 사용하여 여러 문자열을 한 번에 치환합니다.

Example:

ReplaceAll("a b c", map[string]string{"a": "x", "b": "y"})  // "x y c"
ReplaceAll("hello world", map[string]string{"hello": "hi", "world": "there"})  // "hi there"

func ReplaceIgnoreCase

func ReplaceIgnoreCase(s, old, new string) string

ReplaceIgnoreCase replaces a substring ignoring case. ReplaceIgnoreCase는 대소문자를 무시하고 부분 문자열을 치환합니다.

Example:

ReplaceIgnoreCase("Hello World", "hello", "hi")  // "hi World"
ReplaceIgnoreCase("HELLO World", "hello", "hi")  // "hi World"

func Reverse

func Reverse(s string) string

Reverse reverses a string (Unicode-safe). Reverse는 문자열을 뒤집습니다 (유니코드 안전).

Example:

Reverse("hello") // "olleh" Reverse("안녕") // "녕안"

func Right(s string, n int) string

Right returns the rightmost n characters of a string (Unicode-safe). Right는 문자열의 가장 오른쪽 n개 문자를 반환합니다 (유니코드 안전).

If n is greater than string length, returns the entire string. n이 문자열 길이보다 크면 전체 문자열을 반환합니다.

Example:

Right("hello world", 5) // "world" Right("안녕하세요", 2) // "세요"

Right("hello", 10)       // "hello"

func RuneCount

func RuneCount(s string) int

RuneCount returns the number of Unicode characters (runes) in a string. RuneCount는 문자열의 유니코드 문자(rune) 개수를 반환합니다.

This is different from len(s) which returns the number of bytes. 이것은 바이트 개수를 반환하는 len(s)와 다릅니다.

Example:

RuneCount("hello") // 5 RuneCount("안녕하세요") // 5 (not 15 bytes)

RuneCount("🔥🔥")      // 2 (not 8 bytes)

func Similarity

func Similarity(a, b string) float64

Similarity calculates the similarity ratio between two strings (0.0 to 1.0). Similarity는 두 문자열 사이의 유사도 비율을 계산합니다 (0.0 ~ 1.0).

Returns 1.0 for identical strings, 0.0 for completely different strings. 동일한 문자열은 1.0, 완전히 다른 문자열은 0.0을 반환합니다.

Formula: 1 - (distance max(len(a), len(b))) 공식: 1 - (거리 max(len(a), len(b)))

Example 예제:

Similarity("hello", "hello")   // 1.0
Similarity("hello", "hallo")   // 0.8
Similarity("hello", "world")   // 0.2

func Slugify

func Slugify(s string) string

Slugify converts a string to a URL-friendly slug. Slugify는 문자열을 URL 친화적인 슬러그로 변환합니다.

Converts to lowercase, replaces spaces and special characters with hyphens, and removes consecutive hyphens. 소문자로 변환하고, 공백과 특수 문자를 하이픈으로 대체하며, 연속된 하이픈을 제거합니다.

Example:

Slugify("Hello World!")           // "hello-world"
Slugify("User Profile Data")      // "user-profile-data"
Slugify("Go Utils -- Package")    // "go-utils-package"

func StartsWithAny

func StartsWithAny(s string, prefixes []string) bool

StartsWithAny returns true if the string starts with any of the prefixes. StartsWithAny는 문자열이 접두사 중 하나로 시작하면 true를 반환합니다.

Example:

StartsWithAny("https://example.com", []string{"http://", "https://"})  // true
StartsWithAny("ftp://example.com", []string{"http://", "https://"})    // false

func Substring

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

Substring extracts a substring from start to end index (Unicode-safe). Substring은 start부터 end 인덱스까지 부분 문자열을 추출합니다 (유니코드 안전).

Parameters: - start: starting index (inclusive) - end: ending index (exclusive)

If indices are out of bounds, they are adjusted to valid range. 인덱스가 범위를 벗어나면 유효한 범위로 조정됩니다.

Example:

Substring("hello world", 0, 5)   // "hello"

Substring("hello world", 6, 11) // "world" Substring("안녕하세요", 0, 2) // "안녕"

Substring("hello", 0, 100)       // "hello" (auto-adjusted)

func SwapCase

func SwapCase(s string) string

SwapCase swaps the case of all letters in a string. SwapCase는 문자열의 모든 글자의 대소문자를 반전합니다.

Uppercase becomes lowercase and vice versa. 대문자는 소문자로, 소문자는 대문자로 변환됩니다.

Example:

SwapCase("Hello World")  // "hELLO wORLD"
SwapCase("GoLang")       // "gOlANG"
SwapCase("ABC123xyz")    // "abc123XYZ"

func ToCamelCase

func ToCamelCase(s string) string

ToCamelCase converts a string to camelCase. ToCamelCase는 문자열을 camelCase로 변환합니다.

Example:

ToCamelCase("user_profile_data")  // "userProfileData"
ToCamelCase("user-profile-data")  // "userProfileData"
ToCamelCase("UserProfileData")    // "userProfileData"

func ToKebabCase

func ToKebabCase(s string) string

ToKebabCase converts a string to kebab-case. ToKebabCase는 문자열을 kebab-case로 변환합니다.

Example:

ToKebabCase("UserProfileData")   // "user-profile-data"
ToKebabCase("user_profile_data") // "user-profile-data"
ToKebabCase("userProfileData")   // "user-profile-data"

func ToPascalCase

func ToPascalCase(s string) string

ToPascalCase converts a string to PascalCase. ToPascalCase는 문자열을 PascalCase로 변환합니다.

Example:

ToPascalCase("user_profile_data") // "UserProfileData"
ToPascalCase("user-profile-data") // "UserProfileData"
ToPascalCase("userProfileData")   // "UserProfileData"

func ToScreamingSnakeCase

func ToScreamingSnakeCase(s string) string

ToScreamingSnakeCase converts a string to SCREAMING_SNAKE_CASE. ToScreamingSnakeCase는 문자열을 SCREAMING_SNAKE_CASE로 변환합니다.

Example:

ToScreamingSnakeCase("UserProfileData") // "USER_PROFILE_DATA"
ToScreamingSnakeCase("userProfileData") // "USER_PROFILE_DATA"

func ToSnakeCase

func ToSnakeCase(s string) string

ToSnakeCase converts a string to snake_case. ToSnakeCase는 문자열을 snake_case로 변환합니다.

Handles multiple input formats: 여러 입력 형식 처리:

  • PascalCase: "UserProfileData" → "user_profile_data"
  • camelCase: "userProfileData" → "user_profile_data"
  • kebab-case: "user-profile-data" → "user_profile_data"
  • SCREAMING_SNAKE_CASE: "USER_PROFILE_DATA" → "user_profile_data"

Example:

ToSnakeCase("UserProfileData")  // "user_profile_data"
ToSnakeCase("userProfileData")  // "user_profile_data"
ToSnakeCase("user-profile-data") // "user_profile_data"

func ToTitle

func ToTitle(s string) string

ToTitle converts a string to Title Case (each word capitalized). ToTitle은 문자열을 Title Case로 변환합니다 (각 단어의 첫 글자를 대문자로).

Example:

ToTitle("hello world")       // "Hello World"
ToTitle("user_profile_data") // "User Profile Data"
ToTitle("hello-world")       // "Hello World"

func Truncate

func Truncate(s string, length int) string

Truncate truncates a string to the specified length and appends "...". Truncate는 문자열을 지정된 길이로 자르고 "..."를 추가합니다.

Unicode-safe: uses rune count, not byte count. 유니코드 안전: 바이트 수가 아닌 rune 수 사용.

Example:

Truncate("Hello World", 8) // "Hello..." Truncate("안녕하세요", 3) // "안녕하..."

func TruncateWithSuffix

func TruncateWithSuffix(s string, length int, suffix string) string

TruncateWithSuffix truncates a string with a custom suffix. TruncateWithSuffix는 사용자 정의 suffix로 문자열을 자릅니다.

Example:

TruncateWithSuffix("Hello World", 8, "…") // "Hello Wo…" TruncateWithSuffix("안녕하세요", 3, "…") // "안녕하…"

func URLDecode

func URLDecode(s string) (string, error)

URLDecode decodes a URL-encoded string. URLDecode는 URL 인코딩된 문자열을 디코딩합니다.

Returns an error if the input is not valid URL encoding. 입력이 유효한 URL 인코딩이 아니면 에러를 반환합니다.

Example 예제:

URLDecode("hello+world")  // "hello world", nil
URLDecode("hello%2Fworld")  // "hello/world", nil

func URLEncode

func URLEncode(s string) string

URLEncode encodes a string for safe use in URLs. URLEncode는 URL에서 안전하게 사용하기 위해 문자열을 인코딩합니다.

Example 예제:

URLEncode("hello world")  // "hello+world"
URLEncode("hello/world")  // "hello%2Fworld"

func Unquote

func Unquote(s string) string

Unquote removes surrounding quotes from a string and unescapes internal quotes. Unquote는 문자열에서 주변 따옴표를 제거하고 내부 따옴표의 이스케이프를 해제합니다.

Supports both double quotes (") and single quotes ('). 큰따옴표(")와 작은따옴표(') 모두 지원합니다.

Example:

Unquote("\"hello\"")       // "hello"
Unquote("'world'")         // "world"
Unquote("\"say \\\"hi\\\"\"") // "say \"hi\""

func Width

func Width(s string) int

Width returns the display width of a string. Width는 문자열의 디스플레이 너비를 반환합니다.

This considers East Asian Width (EAW) properties: 동아시아 너비(EAW) 속성을 고려합니다: - ASCII characters (a-z, 0-9): width 1 - CJK characters (한글, 漢字, etc): width 2

  • Emoji: typically width 2

Example:

Width("hello") // 5 Width("안녕") // 4 (2 characters × 2 width each)

Width("hello세계")   // 9 (5 + 4)

func Words

func Words(s string) []string

Words splits a string by whitespace. Words는 공백으로 문자열을 분리합니다.

Example:

Words("hello world foo")  // ["hello", "world", "foo"]
Words("  a  b  c  ")       // ["a", "b", "c"]

func WrapText

func WrapText(s string, width int) string

WrapText wraps text to the specified line width. WrapText는 텍스트를 지정된 줄 너비로 줄바꿈합니다.

Example 예제:

WrapText("The quick brown fox jumps", 10)
// "The quick\nbrown fox\njumps"

Types

type StringBuilder

type StringBuilder struct {
	// contains filtered or unexported fields
}

StringBuilder provides a fluent API for chaining string operations. StringBuilder는 문자열 작업을 체이닝하기 위한 fluent API를 제공합니다.

Example 예제:

result := stringutil.NewBuilder().
	Append("user profile data").
	Clean().
	ToSnakeCase().
	Truncate(20).
	Build()

func NewBuilder

func NewBuilder() *StringBuilder

NewBuilder creates a new StringBuilder. NewBuilder는 새 StringBuilder를 생성합니다.

Example 예제:

sb := stringutil.NewBuilder()

func NewBuilderWithString

func NewBuilderWithString(s string) *StringBuilder

NewBuilderWithString creates a new StringBuilder with an initial string. NewBuilderWithString은 초기 문자열로 새 StringBuilder를 생성합니다.

Example 예제:

sb := stringutil.NewBuilderWithString("hello")

func (*StringBuilder) Append

func (sb *StringBuilder) Append(s string) *StringBuilder

Append appends a string to the builder. Append는 빌더에 문자열을 추가합니다.

Example 예제:

sb.Append("hello").Append(" world")

func (*StringBuilder) AppendLine

func (sb *StringBuilder) AppendLine(s string) *StringBuilder

AppendLine appends a string followed by a newline. AppendLine은 문자열 뒤에 줄바꿈을 추가합니다.

Example 예제:

sb.AppendLine("line1").AppendLine("line2")

func (*StringBuilder) Build

func (sb *StringBuilder) Build() string

Build returns the final string value. Build는 최종 문자열 값을 반환합니다.

Example 예제:

result := sb.Append("hello").ToUpper().Build()  // "HELLO"

func (*StringBuilder) Capitalize

func (sb *StringBuilder) Capitalize() *StringBuilder

Capitalize capitalizes each word in the current value. Capitalize는 현재 값의 각 단어를 대문자로 시작하게 합니다.

Example 예제:

sb.Append("hello world").Capitalize().Build()  // "Hello World"

func (*StringBuilder) CapitalizeFirst

func (sb *StringBuilder) CapitalizeFirst() *StringBuilder

CapitalizeFirst capitalizes only the first letter. CapitalizeFirst는 첫 글자만 대문자로 변환합니다.

Example 예제:

sb.Append("hello world").CapitalizeFirst().Build()  // "Hello world"

func (*StringBuilder) Clean

func (sb *StringBuilder) Clean() *StringBuilder

Clean trims and deduplicates spaces. Clean은 공백을 제거하고 중복 공백을 정리합니다.

Example 예제:

sb.Append("  hello   world  ").Clean().Build()  // "hello world"

func (*StringBuilder) Len

func (sb *StringBuilder) Len() int

Len returns the length of the current value in runes (Unicode-safe). Len은 현재 값의 길이를 rune 단위로 반환합니다 (유니코드 안전).

func (*StringBuilder) PadLeft

func (sb *StringBuilder) PadLeft(length int, pad string) *StringBuilder

PadLeft pads the current value on the left side to reach the specified length. PadLeft는 지정된 길이에 도달하도록 현재 값의 왼쪽에 패딩을 추가합니다.

Example 예제:

sb.Append("5").PadLeft(3, "0").Build()  // "005"

func (*StringBuilder) PadRight

func (sb *StringBuilder) PadRight(length int, pad string) *StringBuilder

PadRight pads the current value on the right side to reach the specified length. PadRight는 지정된 길이에 도달하도록 현재 값의 오른쪽에 패딩을 추가합니다.

Example 예제:

sb.Append("5").PadRight(3, "0").Build()  // "500"

func (*StringBuilder) Quote

func (sb *StringBuilder) Quote() *StringBuilder

Quote wraps the current value in double quotes. Quote는 현재 값을 큰따옴표로 감쌉니다.

Example 예제:

sb.Append("hello").Quote().Build()  // "\"hello\""

func (*StringBuilder) RemoveSpaces

func (sb *StringBuilder) RemoveSpaces() *StringBuilder

RemoveSpaces removes all whitespace. RemoveSpaces는 모든 공백을 제거합니다.

Example 예제:

sb.Append("hello world").RemoveSpaces().Build()  // "helloworld"

func (*StringBuilder) RemoveSpecialChars

func (sb *StringBuilder) RemoveSpecialChars() *StringBuilder

RemoveSpecialChars removes all special characters (keeps only alphanumeric). RemoveSpecialChars는 모든 특수 문자를 제거합니다 (영숫자만 유지).

Example 예제:

sb.Append("hello@world!").RemoveSpecialChars().Build()  // "helloworld"

func (*StringBuilder) Repeat

func (sb *StringBuilder) Repeat(count int) *StringBuilder

Repeat repeats the current value count times. Repeat는 현재 값을 count번 반복합니다.

Example 예제:

sb.Append("ab").Repeat(3).Build()  // "ababab"

func (*StringBuilder) Replace

func (sb *StringBuilder) Replace(old, new string) *StringBuilder

Replace replaces all occurrences of old with new. Replace는 old를 모두 new로 치환합니다.

Example 예제:

sb.Append("hello world").Replace("world", "there").Build()  // "hello there"

func (*StringBuilder) Reset

func (sb *StringBuilder) Reset() *StringBuilder

Reset resets the builder to an empty string. Reset은 빌더를 빈 문자열로 초기화합니다.

func (*StringBuilder) Reverse

func (sb *StringBuilder) Reverse() *StringBuilder

Reverse reverses the current value (Unicode-safe). Reverse는 현재 값을 뒤집습니다 (유니코드 안전).

Example 예제:

sb.Append("hello").Reverse().Build()  // "olleh"

func (*StringBuilder) Slugify

func (sb *StringBuilder) Slugify() *StringBuilder

Slugify converts the current value to a URL-friendly slug. Slugify는 현재 값을 URL 친화적인 slug로 변환합니다.

Example 예제:

sb.Append("Hello World!").Slugify().Build()  // "hello-world"

func (*StringBuilder) String

func (sb *StringBuilder) String() string

String returns the current string value (implements fmt.Stringer). String은 현재 문자열 값을 반환합니다 (fmt.Stringer 인터페이스 구현).

func (*StringBuilder) ToCamelCase

func (sb *StringBuilder) ToCamelCase() *StringBuilder

ToCamelCase converts the current value to camelCase. ToCamelCase는 현재 값을 camelCase로 변환합니다.

Example 예제:

sb.Append("user_profile").ToCamelCase().Build()  // "userProfile"

func (*StringBuilder) ToKebabCase

func (sb *StringBuilder) ToKebabCase() *StringBuilder

ToKebabCase converts the current value to kebab-case. ToKebabCase는 현재 값을 kebab-case로 변환합니다.

Example 예제:

sb.Append("UserProfile").ToKebabCase().Build()  // "user-profile"

func (*StringBuilder) ToLower

func (sb *StringBuilder) ToLower() *StringBuilder

ToLower converts the current value to lowercase. ToLower는 현재 값을 소문자로 변환합니다.

Example 예제:

sb.Append("HELLO").ToLower().Build()  // "hello"

func (*StringBuilder) ToPascalCase

func (sb *StringBuilder) ToPascalCase() *StringBuilder

ToPascalCase converts the current value to PascalCase. ToPascalCase는 현재 값을 PascalCase로 변환합니다.

Example 예제:

sb.Append("user_profile").ToPascalCase().Build()  // "UserProfile"

func (*StringBuilder) ToSnakeCase

func (sb *StringBuilder) ToSnakeCase() *StringBuilder

ToSnakeCase converts the current value to snake_case. ToSnakeCase는 현재 값을 snake_case로 변환합니다.

Example 예제:

sb.Append("UserProfile").ToSnakeCase().Build()  // "user_profile"

func (*StringBuilder) ToTitle

func (sb *StringBuilder) ToTitle() *StringBuilder

ToTitle converts the current value to Title Case. ToTitle은 현재 값을 Title Case로 변환합니다.

Example 예제:

sb.Append("hello world").ToTitle().Build()  // "Hello World"

func (*StringBuilder) ToUpper

func (sb *StringBuilder) ToUpper() *StringBuilder

ToUpper converts the current value to uppercase. ToUpper는 현재 값을 대문자로 변환합니다.

Example 예제:

sb.Append("hello").ToUpper().Build()  // "HELLO"

func (*StringBuilder) Trim

func (sb *StringBuilder) Trim() *StringBuilder

Trim removes leading and trailing whitespace. Trim은 앞뒤 공백을 제거합니다.

Example 예제:

sb.Append("  hello  ").Trim().Build()  // "hello"

func (*StringBuilder) Truncate

func (sb *StringBuilder) Truncate(length int) *StringBuilder

Truncate truncates the current value to the specified length and appends "...". Truncate는 현재 값을 지정된 길이로 자르고 "..."를 추가합니다.

Example 예제:

sb.Append("Hello World").Truncate(8).Build()  // "Hello..."

func (*StringBuilder) TruncateWithSuffix

func (sb *StringBuilder) TruncateWithSuffix(length int, suffix string) *StringBuilder

TruncateWithSuffix truncates the current value with a custom suffix. TruncateWithSuffix는 현재 값을 사용자 정의 suffix로 자릅니다.

Example 예제:

sb.Append("Hello World").TruncateWithSuffix(8, "…").Build()  // "Hello Wo…"

func (*StringBuilder) Unquote

func (sb *StringBuilder) Unquote() *StringBuilder

Unquote removes surrounding quotes. Unquote는 주변 따옴표를 제거합니다.

Example 예제:

sb.Append("\"hello\"").Unquote().Build()  // "hello"

Jump to

Keyboard shortcuts

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