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 ¶
- func AddLineNumbers(s string) string
- func Base64Decode(s string) (string, error)
- func Base64Encode(s string) string
- func Base64URLDecode(s string) (string, error)
- func Base64URLEncode(s string) string
- func Capitalize(s string) string
- func CapitalizeFirst(s string) string
- func Clean(s string) string
- func ContainsAll(s string, substrs []string) bool
- func ContainsAny(s string, substrs []string) bool
- func CountOccurrences(s, substr string) int
- func CountWords(s string) int
- func Dedent(s string) string
- func Ellipsis(s string, maxLen int) string
- func EndsWithAny(s string, suffixes []string) bool
- func EqualFold(s1, s2 string) bool
- func Filter(strs []string, fn func(string) bool) []string
- func FormatBytes(bytes int64) string
- func FormatNumber(n int, separator string) string
- func FormatWithCount(count int, singular, plural string) string
- func HTMLEscape(s string) string
- func HTMLUnescape(s string) string
- func HammingDistance(a, b string) int
- func HasPrefix(s, prefix string) bool
- func HasSuffix(s, suffix string) bool
- func Indent(s string, prefix string) string
- func Insert(s string, index int, insert string) string
- func IsAlpha(s string) bool
- func IsAlphanumeric(s string) bool
- func IsBlank(s string) bool
- func IsEmail(s string) bool
- func IsLower(s string) bool
- func IsNumeric(s string) bool
- func IsURL(s string) bool
- func IsUpper(s string) bool
- func JaroWinklerSimilarity(a, b string) float64
- func Join(strs []string, sep string) string
- func Left(s string, n int) string
- func LevenshteinDistance(a, b string) int
- func Lines(s string) []string
- func Map(strs []string, fn func(string) string) []string
- func Mask(s string, first, last int, maskChar string) string
- func MaskCreditCard(card string) string
- func MaskEmail(email string) string
- func Normalize(s string, form string) string
- func PadLeft(s string, length int, pad string) string
- func PadRight(s string, length int, pad string) string
- func Pluralize(count int, singular, plural string) string
- func Quote(s string) string
- func RemoveDuplicates(s string) string
- func RemoveSpaces(s string) string
- func RemoveSpecialChars(s string) string
- func Repeat(s string, count int) string
- func ReplaceAll(s string, replacements map[string]string) string
- func ReplaceIgnoreCase(s, old, new string) string
- func Reverse(s string) string
- func Right(s string, n int) string
- func RuneCount(s string) int
- func Similarity(a, b string) float64
- func Slugify(s string) string
- func StartsWithAny(s string, prefixes []string) bool
- func Substring(s string, start, end int) string
- func SwapCase(s string) string
- func ToCamelCase(s string) string
- func ToKebabCase(s string) string
- func ToPascalCase(s string) string
- func ToScreamingSnakeCase(s string) string
- func ToSnakeCase(s string) string
- func ToTitle(s string) string
- func Truncate(s string, length int) string
- func TruncateWithSuffix(s string, length int, suffix string) string
- func URLDecode(s string) (string, error)
- func URLEncode(s string) string
- func Unquote(s string) string
- func Width(s string) int
- func Words(s string) []string
- func WrapText(s string, width int) string
- type StringBuilder
- func (sb *StringBuilder) Append(s string) *StringBuilder
- func (sb *StringBuilder) AppendLine(s string) *StringBuilder
- func (sb *StringBuilder) Build() string
- func (sb *StringBuilder) Capitalize() *StringBuilder
- func (sb *StringBuilder) CapitalizeFirst() *StringBuilder
- func (sb *StringBuilder) Clean() *StringBuilder
- func (sb *StringBuilder) Len() int
- func (sb *StringBuilder) PadLeft(length int, pad string) *StringBuilder
- func (sb *StringBuilder) PadRight(length int, pad string) *StringBuilder
- func (sb *StringBuilder) Quote() *StringBuilder
- func (sb *StringBuilder) RemoveSpaces() *StringBuilder
- func (sb *StringBuilder) RemoveSpecialChars() *StringBuilder
- func (sb *StringBuilder) Repeat(count int) *StringBuilder
- func (sb *StringBuilder) Replace(old, new string) *StringBuilder
- func (sb *StringBuilder) Reset() *StringBuilder
- func (sb *StringBuilder) Reverse() *StringBuilder
- func (sb *StringBuilder) Slugify() *StringBuilder
- func (sb *StringBuilder) String() string
- func (sb *StringBuilder) ToCamelCase() *StringBuilder
- func (sb *StringBuilder) ToKebabCase() *StringBuilder
- func (sb *StringBuilder) ToLower() *StringBuilder
- func (sb *StringBuilder) ToPascalCase() *StringBuilder
- func (sb *StringBuilder) ToSnakeCase() *StringBuilder
- func (sb *StringBuilder) ToTitle() *StringBuilder
- func (sb *StringBuilder) ToUpper() *StringBuilder
- func (sb *StringBuilder) Trim() *StringBuilder
- func (sb *StringBuilder) Truncate(length int) *StringBuilder
- func (sb *StringBuilder) TruncateWithSuffix(length int, suffix string) *StringBuilder
- func (sb *StringBuilder) Unquote() *StringBuilder
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddLineNumbers ¶
AddLineNumbers adds line numbers to each line of text. AddLineNumbers는 텍스트의 각 줄에 줄 번호를 추가합니다.
Example 예제:
AddLineNumbers("line1\nline2\nline3")
// "1: line1\n2: line2\n3: line3"
func Base64Decode ¶
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 ¶
Base64Encode encodes a string to base64. Base64Encode는 문자열을 base64로 인코딩합니다.
Example 예제:
Base64Encode("hello") // "aGVsbG8="
func Base64URLDecode ¶
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 ¶
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 ¶
Capitalize capitalizes the first letter of each word. Capitalize는 각 단어의 첫 글자를 대문자로 만듭니다.
Example:
Capitalize("hello world") // "Hello World"
Capitalize("hello-world") // "Hello-World"
func CapitalizeFirst ¶
CapitalizeFirst capitalizes only the first letter of the string. CapitalizeFirst는 문자열의 첫 글자만 대문자로 만듭니다.
Example:
CapitalizeFirst("hello world") // "Hello world"
CapitalizeFirst("HELLO WORLD") // "HELLO WORLD"
func Clean ¶
Clean trims whitespace and deduplicates spaces. Clean은 공백을 제거하고 중복 공백을 정리합니다.
Example:
Clean(" hello world ") // "hello world"
Clean("\t\nhello\t\nworld") // "hello world"
func ContainsAll ¶
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 ¶
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 ¶
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 ¶
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 ¶
Dedent removes common leading whitespace from each line. Dedent는 각 줄에서 공통 선행 공백을 제거합니다.
Example 예제:
Dedent(" line1\n line2") // "line1\nline2"
Dedent(" line1\n line2") // " line1\nline2"
func Ellipsis ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
HTMLEscape escapes special HTML characters. HTMLEscape는 특수 HTML 문자를 이스케이프합니다.
Escapes: <, >, &, ", ' 이스케이프: <, >, &, ", '
Example 예제:
HTMLEscape("<div>hello</div>") // "<div>hello</div>"
HTMLEscape("'hello' & \"world\"") // "'hello' & "world""
func HTMLUnescape ¶
HTMLUnescape unescapes HTML entities. HTMLUnescape는 HTML 엔티티를 언이스케이프합니다.
Example 예제:
HTMLUnescape("<div>hello</div>") // "<div>hello</div>"
HTMLUnescape("'hello' & "world"") // "'hello' & \"world\""
func HammingDistance ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Lines splits a string by newlines. Lines는 줄바꿈으로 문자열을 분리합니다.
Example:
Lines("line1\nline2\nline3") // ["line1", "line2", "line3"]
Lines("a\nb\nc") // ["a", "b", "c"]
func Map ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Quote wraps a string in double quotes and escapes internal quotes. Quote는 문자열을 큰따옴표로 감싸고 내부 따옴표를 이스케이프합니다.
Example:
Quote("hello") // "\"hello\""
Quote("say \"hi\"") // "\"say \\\"hi\\\"\""
func RemoveDuplicates ¶
RemoveDuplicates removes duplicate characters from a string. RemoveDuplicates는 문자열에서 중복 문자를 제거합니다.
Example:
RemoveDuplicates("hello") // "helo"
RemoveDuplicates("aabbcc") // "abc"
func RemoveSpaces ¶
RemoveSpaces removes all whitespace from a string. RemoveSpaces는 문자열에서 모든 공백을 제거합니다.
Example:
RemoveSpaces("h e l l o") // "hello"
RemoveSpaces(" hello world ") // "helloworld"
func RemoveSpecialChars ¶
RemoveSpecialChars removes special characters, keeping only alphanumeric and spaces. RemoveSpecialChars는 특수 문자를 제거하고 영숫자와 공백만 유지합니다.
Example:
RemoveSpecialChars("hello@#$123") // "hello123"
RemoveSpecialChars("a!b@c#123") // "abc123"
func Repeat ¶
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 ¶
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 ¶
ReplaceIgnoreCase replaces a substring ignoring case. ReplaceIgnoreCase는 대소문자를 무시하고 부분 문자열을 치환합니다.
Example:
ReplaceIgnoreCase("Hello World", "hello", "hi") // "hi World"
ReplaceIgnoreCase("HELLO World", "hello", "hi") // "hi World"
func Reverse ¶
Reverse reverses a string (Unicode-safe). Reverse는 문자열을 뒤집습니다 (유니코드 안전).
Example:
Reverse("hello") // "olleh" Reverse("안녕") // "녕안"
func Right ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ToCamelCase converts a string to camelCase. ToCamelCase는 문자열을 camelCase로 변환합니다.
Example:
ToCamelCase("user_profile_data") // "userProfileData"
ToCamelCase("user-profile-data") // "userProfileData"
ToCamelCase("UserProfileData") // "userProfileData"
func ToKebabCase ¶
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 ¶
ToPascalCase converts a string to PascalCase. ToPascalCase는 문자열을 PascalCase로 변환합니다.
Example:
ToPascalCase("user_profile_data") // "UserProfileData"
ToPascalCase("user-profile-data") // "UserProfileData"
ToPascalCase("userProfileData") // "UserProfileData"
func ToScreamingSnakeCase ¶
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 ¶
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 ¶
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 ¶
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 ¶
TruncateWithSuffix truncates a string with a custom suffix. TruncateWithSuffix는 사용자 정의 suffix로 문자열을 자릅니다.
Example:
TruncateWithSuffix("Hello World", 8, "…") // "Hello Wo…" TruncateWithSuffix("안녕하세요", 3, "…") // "안녕하…"
func URLDecode ¶
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 ¶
URLEncode encodes a string for safe use in URLs. URLEncode는 URL에서 안전하게 사용하기 위해 문자열을 인코딩합니다.
Example 예제:
URLEncode("hello world") // "hello+world"
URLEncode("hello/world") // "hello%2Fworld"
func Unquote ¶
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 ¶
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)
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"