diff options
| author | Robert Griesemer <gri@golang.org> | 2010-03-26 13:05:04 -0700 |
|---|---|---|
| committer | Robert Griesemer <gri@golang.org> | 2010-03-26 13:05:04 -0700 |
| commit | d0ffee8abfad42e632129848b1f8ab9efcfa6ce9 (patch) | |
| tree | 3f9d9457659ce6a0c93d3b8fd966442b6043d467 /src/pkg/strings | |
| parent | 9e481e2905f5ddacf603fa2c0d9fc555c211f71b (diff) | |
| download | go-d0ffee8abfad42e632129848b1f8ab9efcfa6ce9.tar.xz | |
bytes, strings: IndexOfAny
+ first use in go/doc
R=r
CC=golang-dev
https://golang.org/cl/781041
Diffstat (limited to 'src/pkg/strings')
| -rw-r--r-- | src/pkg/strings/strings.go | 15 | ||||
| -rw-r--r-- | src/pkg/strings/strings_test.go | 19 |
2 files changed, 31 insertions, 3 deletions
diff --git a/src/pkg/strings/strings.go b/src/pkg/strings/strings.go index a8f3150c3e..1ceaeefbd4 100644 --- a/src/pkg/strings/strings.go +++ b/src/pkg/strings/strings.go @@ -106,6 +106,21 @@ func LastIndex(s, sep string) int { return -1 } +// IndexAny returns the index of the first instance of any Unicode code point +// from chars in s, or -1 if no Unicode code point from chars is present in s. +func IndexAny(s, chars string) int { + if len(chars) > 0 { + for i, c := range s { + for _, m := range chars { + if c == m { + return i + } + } + } + } + return -1 +} + // Generic split: splits after each instance of sep, // including sepSave bytes of sep in the subarrays. func genSplit(s, sep string, sepSave, n int) []string { diff --git a/src/pkg/strings/strings_test.go b/src/pkg/strings/strings_test.go index a88f6aae4d..fdf192db63 100644 --- a/src/pkg/strings/strings_test.go +++ b/src/pkg/strings/strings_test.go @@ -72,6 +72,20 @@ var lastIndexTests = []IndexTest{ IndexTest{"abcABCabc", "a", 6}, } +var indexAnyTests = []IndexTest{ + IndexTest{"", "", -1}, + IndexTest{"", "a", -1}, + IndexTest{"", "abc", -1}, + IndexTest{"a", "", -1}, + IndexTest{"a", "a", 0}, + IndexTest{"aaa", "a", 0}, + IndexTest{"abc", "xyz", -1}, + IndexTest{"abc", "xcz", 2}, + IndexTest{"a☺b☻c☹d", "uvw☻xyz", 2 + len("☺")}, + IndexTest{"aRegExp*", ".(|)*+?^$[]", 7}, + IndexTest{dots + dots + dots, " ", -1}, +} + // Execute f on each test case. funcName should be the name of f; it's used // in failure reports. func runIndexTests(t *testing.T, f func(s, sep string) int, funcName string, testCases []IndexTest) { @@ -83,10 +97,9 @@ func runIndexTests(t *testing.T, f func(s, sep string) int, funcName string, tes } } -func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) } - +func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) } func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) } - +func TestIndexAny(t *testing.T) { runIndexTests(t, IndexAny, "IndexAny", indexAnyTests) } type ExplodeTest struct { s string |
