strings.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import "strings"
  15. // InStringSlice checks whether a string is inside a string slice.
  16. // Comparison is case insensitive.
  17. func InStringSlice(ss []string, str string) bool {
  18. for _, s := range ss {
  19. if strings.ToLower(s) == strings.ToLower(str) {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. // SubtractStringSlice subtracts string from string slice.
  26. // Comparison is case insensitive.
  27. func SubtractStringSlice(ss []string, str string) []string {
  28. var res []string
  29. for _, s := range ss {
  30. if strings.ToLower(s) == strings.ToLower(str) {
  31. continue
  32. }
  33. res = append(res, s)
  34. }
  35. return res
  36. }
  37. // MergeStringSlices merges 2 string slices into one and remove duplicated elements.
  38. func MergeStringSlices(a []string, b []string) []string {
  39. set := map[string]struct{}{}
  40. for _, s := range a {
  41. set[s] = struct{}{}
  42. }
  43. for _, s := range b {
  44. set[s] = struct{}{}
  45. }
  46. var ss []string
  47. for s := range set {
  48. ss = append(ss, s)
  49. }
  50. return ss
  51. }