diff --git a/.idea/golinter.xml b/.idea/golinter.xml new file mode 100644 index 0000000..fc943aa --- /dev/null +++ b/.idea/golinter.xml @@ -0,0 +1,35 @@ + + + + + + \ No newline at end of file diff --git a/Changes.md b/Changes.md index 43f444d..33c890f 100644 --- a/Changes.md +++ b/Changes.md @@ -1,3 +1,7 @@ +## WIP TBD + + * Adding `strings.TrimToOnly`. + ## v0.9.1 2024-10-15 * :hammer: Fixed buf in `strings.Indent` that caused a panic if the input string was empty. diff --git a/README.md b/README.md index b0f5b46..0d2f6bb 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ provided tools: Here's a few additional operations for working with slices of bytes: * `ContainsOnly(b, chars)` +* `TrimToOnly(b, chars)` * `FromRange(a, z)` * `Reverse(b)` * `Indent(b, indent)` diff --git a/strings/content.go b/strings/content.go index 6ed00ae..c556ae3 100644 --- a/strings/content.go +++ b/strings/content.go @@ -18,6 +18,19 @@ func ContainsOnly(s, chars string) bool { }) == -1 } +// TrimToOnly returns the string with all characters removed that are not in the +// given set of characters. +func TrimToOnly(s string, chars string) string { + var out []rune + for _, r := range s { + if strings.ContainsRune(chars, r) { + out = append(out, r) + break + } + } + return string(out) +} + type runeSlice []rune // func (rs runeSlice) Less(i, j int) bool { diff --git a/strings/content_test.go b/strings/content_test.go index 9723e88..c1c31b2 100644 --- a/strings/content_test.go +++ b/strings/content_test.go @@ -17,6 +17,17 @@ func TestContainsOnly(t *testing.T) { assert.False(t, strings.ContainsOnly("a b c", "abc")) } +func TestTrimToOnly(t *testing.T) { + t.Parallel() + + assert.Equal(t, "abc", strings.TrimToOnly("abc", "abc")) + assert.Equal(t, "a", strings.TrimToOnly("a", "abc")) + assert.Equal(t, "aaaaaabbbbbbccccc", strings.TrimToOnly("aaaaaabbbbbbccccc", "cba")) + assert.Equal(t, "abc", strings.TrimToOnly("a b c", "abc")) + assert.Equal(t, "", strings.TrimToOnly("abc", "def")) + assert.Equal(t, "abde", strings.TrimToOnly("abcdef", "adbe")) +} + func TestFromRange(t *testing.T) { t.Parallel()