ADDED:
* stringsx.RemoveWhitespace, stringsx.StripWhitespace
This commit is contained in:
brent saner
2026-07-06 16:21:07 -04:00
parent 58556d7281
commit 42c0e48081
5 changed files with 174 additions and 12 deletions
+73 -10
View File
@@ -1,13 +1,13 @@
package stringsx
import (
`bytes`
`errors`
`fmt`
`io`
`slices`
`strings`
`unicode`
"bytes"
"errors"
"fmt"
"io"
"slices"
"strings"
"unicode"
)
/*
@@ -17,6 +17,7 @@ It is more strict than [HasBoundary] (which only requires
that s has sym at the beginning OR the end.)
Examples:
HasBookend("|foo|", "|") → true
HasBookend("|foo", "|") → false
HasBookend("foo|", "|") → false
@@ -38,6 +39,7 @@ func HasBookend(s, sym string) (bounded bool) {
HasBoundary returns true if string s starts OR ends with symbol sym.
Examples:
HasBoundary("|foo|", "|") → true
HasBoundary("|foo", "|") → true
HasBoundary("foo|", "|") → true
@@ -51,9 +53,9 @@ If sym is empty, HasBoundary will *always* return true.
If you instead require string s to be *enclosed* by sym, see [HasBookend].
*/
func HasBoundary(s, sym string) (bounded bool) {
bounded = strings.HasPrefix(s, sym) || strings.HasSuffix(s, sym)
return
}
@@ -453,6 +455,37 @@ func Redact(s, maskStr string, leading, trailing uint, newlines bool) (redacted
return
}
/*
RemoveWhitespace removes all leading, trailing, and INNER whitespace
from unicode string `s`.
This is done by allocating a strings.Builder with len(s).
This may consume more memory than needed if s is mostly whitespace;
in that case, it is better to use [StripWhitespace].
*/
func RemoveWhitespace(s string) (removed string) {
// https://stackoverflow.com/questions/32081808/strip-all-whitespace-from-a-string/32081891#32081891
var c rune
var sb strings.Builder
if s == "" {
return
}
sb.Grow(len(s))
for _, c = range s {
if !unicode.IsSpace(c) {
sb.WriteRune(c)
}
}
removed = sb.String()
return
}
// Reverse reverses string s. (It's absolutely insane that this isn't in stdlib.)
func Reverse(s string) (revS string) {
@@ -465,6 +498,35 @@ func Reverse(s string) (revS string) {
return
}
/*
StripWhitespace removes all leading, trailing, and INNER whitespace
from unicode string `s`.
This is done by mapping each rune in `s`.
This may use far more allocations than necessary if `s` is mostly NON-whitespace;
in that case, it is better to use [RemoveWhitespace].
*/
func StripWhitespace(s string) (stripped string) {
// https://stackoverflow.com/questions/32081808/strip-all-whitespace-from-a-string/32081891#32081891
if s == "" {
return
}
stripped = strings.Map(
func(c rune) rune {
if unicode.IsSpace(c) {
return -1
}
return c
},
s,
)
return
}
/*
TrimLines is like [strings.TrimSpace] but operates on *each line* of s.
It is *NIX-newline (`\n`) vs. Windows-newline (`\r\n`) agnostic.
@@ -500,7 +562,8 @@ func TrimLines(s string, left, right bool) (trimmed string) {
} else if right {
sl = TrimSpaceRight(sl)
}
sb.WriteString(sl + nl)
sb.WriteString(sl)
sb.WriteString(nl)
}
trimmed = sb.String()