Feature/cut (#102)

This commit is contained in:
jefferyjob
2025-07-23 15:03:25 +08:00
committed by GitHub
parent e7323b7144
commit 11fdc4d3ca
4 changed files with 80 additions and 2 deletions
+8 -2
View File
@@ -4,10 +4,16 @@ import "fmt"
func ExampleTernary() {
age := 15
res := Ternary(age < 18, "未成年", "成年")
res1 := Ternary(age < 18, "未成年", "成年")
res2 := Ternary(true, "Yes", "No")
res3 := Ternary(false, "Yes", "No")
fmt.Println(res)
fmt.Println(res1)
fmt.Println(res2)
fmt.Println(res3)
// Output:
// 未成年
// Yes
// No
}
+21
View File
@@ -0,0 +1,21 @@
package strx
import "strings"
// Cut 删除 s 中出现的 sub 字符串
// 第三个参数 n 可选:
// - 省略 → 删除所有匹配(等价 strings.ReplaceAll
// - n == 1 → 只删除第一次出现
// - n > 1 → 删除前 n 次出现
func Cut(s, sub string, n ...int) string {
if len(sub) == 0 || len(s) == 0 {
return s // nothing to do
}
// 默认: 删除所有
count := -1
if len(n) > 0 {
count = n[0]
}
return strings.Replace(s, sub, "", count)
}
+14
View File
@@ -0,0 +1,14 @@
package strx
import (
"fmt"
)
func ExampleCut() {
fmt.Println(Cut("this is-AAA", "A"))
fmt.Println(Cut("this is-AAA", "A", 1))
// Output:
// this is-
// this is-AA
}
+37
View File
@@ -0,0 +1,37 @@
package strx
import (
"testing"
)
func TestCut(t *testing.T) {
tests := []struct {
name string
s string
sub string
n int
expected string
}{
{"Remove all", "hello world world", "world", 0, "hello "},
{"Remove once", "hello world world", "world", 1, "hello world"},
{"No sub", "hello world", "", 0, "hello world"},
{"No match", "hello world", "abc", 0, "hello world"},
{"Empty string", "", "world", 0, ""},
{"Remove twice max", "go go go", "go", 2, " go"},
{"Remove all with zero count", "go go go", "go", 0, " "},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var result string
if tt.n > 0 {
result = Cut(tt.s, tt.sub, tt.n)
} else {
result = Cut(tt.s, tt.sub)
}
if result != tt.expected {
t.Errorf("Cut(%q, %q, %v) = %q; want %q", tt.s, tt.sub, tt.n, result, tt.expected)
}
})
}
}