diff --git a/anyx/ternary_example_test.go b/anyx/ternary_example_test.go index 977ad18..cbddd75 100644 --- a/anyx/ternary_example_test.go +++ b/anyx/ternary_example_test.go @@ -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 } diff --git a/strx/cut.go b/strx/cut.go new file mode 100644 index 0000000..c0654d8 --- /dev/null +++ b/strx/cut.go @@ -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) +} diff --git a/strx/cut_example_test.go b/strx/cut_example_test.go new file mode 100644 index 0000000..284565d --- /dev/null +++ b/strx/cut_example_test.go @@ -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 +} diff --git a/strx/cut_test.go b/strx/cut_test.go new file mode 100644 index 0000000..abd0d98 --- /dev/null +++ b/strx/cut_test.go @@ -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) + } + }) + } +}