diff --git a/src/strings/example_test.go b/src/strings/example_test.go index bdab7ae8dea..5a79b42e625 100644 --- a/src/strings/example_test.go +++ b/src/strings/example_test.go @@ -172,6 +172,15 @@ func ExampleHasPrefix() { // true } +func ExampleHasAnyOfPrefixes() { + fmt.Println(strings.HasAnyOfPrefixes("Gopher", "Go", "pher")) + fmt.Println(strings.HasAnyOfPrefixes("Gopher", "C", "D")) + fmt.Println(strings.HasAnyOfPrefixes("Gopher", "")) + // Output: + // true + // false + // true +} func ExampleHasSuffix() { fmt.Println(strings.HasSuffix("Amigo", "go")) fmt.Println(strings.HasSuffix("Amigo", "O")) @@ -184,6 +193,17 @@ func ExampleHasSuffix() { // true } +func ExampleHasAnyOfSuffixes() { + fmt.Println(strings.HasAnyOfSuffixes("Amigo", "go", "Am")) + fmt.Println(strings.HasAnyOfSuffixes("Amigo", "O", "p")) + fmt.Println(strings.HasAnyOfSuffixes("Amigo", "Ami", "Am")) + fmt.Println(strings.HasAnyOfSuffixes("Amigo", "")) + // Output: + // true + // false + // false + // true +} func ExampleIndex() { fmt.Println(strings.Index("chicken", "ken")) fmt.Println(strings.Index("chicken", "dmr")) diff --git a/src/strings/strings.go b/src/strings/strings.go index f3f0723721f..4e68d03d5bc 100644 --- a/src/strings/strings.go +++ b/src/strings/strings.go @@ -468,6 +468,28 @@ func HasSuffix(s, suffix string) bool { return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix } +// HasAnyOfSuffixes returns true if the given string has any of the given suffixes. +func HasAnyOfSuffixes(input string, suffixes ...string) bool { + for _, suffix := range suffixes { + if HasSuffix(input, suffix) { + return true + } + } + + return false +} + +// HasAnyOfPrefixes returns true if the given string has any of the given prefixes. +func HasAnyOfPrefixes(input string, prefixes ...string) bool { + for _, prefix := range prefixes { + if HasPrefix(input, prefix) { + return true + } + } + + return false +} + // Map returns a copy of the string s with all its characters modified // according to the mapping function. If mapping returns a negative value, the character is // dropped from the string with no replacement.