aboutsummaryrefslogtreecommitdiff
path: root/src/strings
diff options
context:
space:
mode:
Diffstat (limited to 'src/strings')
-rw-r--r--src/strings/strings.go11
-rw-r--r--src/strings/strings_test.go21
2 files changed, 32 insertions, 0 deletions
diff --git a/src/strings/strings.go b/src/strings/strings.go
index 367e0a8e24..70297f1e69 100644
--- a/src/strings/strings.go
+++ b/src/strings/strings.go
@@ -1289,3 +1289,14 @@ func CutPrefix(s, prefix string) (after string, found bool) {
func CutSuffix(s, suffix string) (before string, found bool) {
return stringslite.CutSuffix(s, suffix)
}
+
+// CutLast slices s around the last instance of sep,
+// returning the text before and after sep.
+// The found result reports whether sep appears in s.
+// If sep does not appear in s, CutLast returns s, "", false.
+func CutLast(s, sep string) (before, after string, found bool) {
+ if i := LastIndex(s, sep); i >= 0 {
+ return s[:i], s[i+len(sep):], true
+ }
+ return s, "", false
+}
diff --git a/src/strings/strings_test.go b/src/strings/strings_test.go
index edfeb0e813..4ff3a2a825 100644
--- a/src/strings/strings_test.go
+++ b/src/strings/strings_test.go
@@ -1826,6 +1826,27 @@ func TestCut(t *testing.T) {
}
}
+func TestCutLast(t *testing.T) {
+ tests := []struct {
+ s, sep string
+ before, after string
+ found bool
+ }{
+ {"a/b/c", "/", "a/b", "c", true},
+ {"a//b//c", "//", "a//b", "c", true},
+ {"abc", "/", "abc", "", false},
+ {"abc", "", "abc", "", true},
+ {"", "", "", "", true},
+ {"/abc", "/", "", "abc", true},
+ {"abc/", "/", "abc", "", true},
+ }
+ for _, tt := range tests {
+ if before, after, found := CutLast(tt.s, tt.sep); before != tt.before || after != tt.after || found != tt.found {
+ t.Errorf("CutLast(%q, %q) = %q, %q, %v; want %q, %q, %v", tt.s, tt.sep, before, after, found, tt.before, tt.after, tt.found)
+ }
+ }
+}
+
var cutPrefixTests = []struct {
s, sep string
after string