diff options
| author | qiulaidongfeng <2645477756@qq.com> | 2026-04-09 22:04:07 +0800 |
|---|---|---|
| committer | Gopher Robot <gobot@golang.org> | 2026-04-14 06:58:23 -0700 |
| commit | 11b596c22dcabf91f9595da778b00e26f4d661a8 (patch) | |
| tree | db66e08f7c03de7facbeab017e68f8f38f255215 /src/bytes | |
| parent | 33241d7298e0c621cfc4cc9f878dba9eff2b1c3d (diff) | |
| download | go-11b596c22dcabf91f9595da778b00e26f4d661a8.tar.xz | |
bytes,strings: add CutLast
Fixes #71151
Change-Id: I3b3d49c35b0fa2c1220d3f39bbd506cc072b52b0
Reviewed-on: https://go-review.googlesource.com/c/go/+/764601
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Diffstat (limited to 'src/bytes')
| -rw-r--r-- | src/bytes/bytes.go | 13 | ||||
| -rw-r--r-- | src/bytes/bytes_test.go | 21 |
2 files changed, 34 insertions, 0 deletions
diff --git a/src/bytes/bytes.go b/src/bytes/bytes.go index 98f78f10c3..2bd1284296 100644 --- a/src/bytes/bytes.go +++ b/src/bytes/bytes.go @@ -1422,3 +1422,16 @@ func CutSuffix(s, suffix []byte) (before []byte, found bool) { } return s[:len(s)-len(suffix)], true } + +// 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, nil, false. +// +// CutLast returns slices of the original slice s, not copies. +func CutLast(s, sep []byte) (before, after []byte, found bool) { + if i := LastIndex(s, sep); i >= 0 { + return s[:i], s[i+len(sep):], true + } + return s, nil, false +} diff --git a/src/bytes/bytes_test.go b/src/bytes/bytes_test.go index 07280464d2..20d333217e 100644 --- a/src/bytes/bytes_test.go +++ b/src/bytes/bytes_test.go @@ -1976,6 +1976,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([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || string(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 |
