String+Utils.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright 2021 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. /// Utilities to simplify String operations.
  18. public extension String {
  19. /// Finds and returns the ranges of all occurrences of a given string within a given range of the String, subject to given options,
  20. /// using the specified locale, if any.
  21. /// - Returns: An an optional array of ranges where each range corresponds to an occurence of the substring in the given string.
  22. func ranges<T: StringProtocol>(of substring: T, options: CompareOptions = .literal,
  23. locale: Locale? = nil) -> [Range<Index>] {
  24. var ranges: [Range<Index>] = []
  25. let end = endIndex
  26. var searchRange = startIndex ..< end
  27. while searchRange.lowerBound < end {
  28. guard let range = range(
  29. of: substring,
  30. options: options,
  31. range: searchRange,
  32. locale: locale
  33. )
  34. else { break }
  35. ranges.append(range)
  36. let shiftedStart = index(range.lowerBound, offsetBy: 1)
  37. searchRange = shiftedStart ..< end
  38. }
  39. return ranges
  40. }
  41. }