String+Utils.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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
  20. /// String, subject to given options,
  21. /// using the specified locale, if any.
  22. /// - Returns: An an optional array of ranges where each range corresponds to an occurrence of the
  23. /// substring in the given string.
  24. func ranges<T: StringProtocol>(of substring: T, options: CompareOptions = .literal,
  25. locale: Locale? = nil) -> [Range<Index>] {
  26. var ranges: [Range<Index>] = []
  27. let end = endIndex
  28. var searchRange = startIndex ..< end
  29. while searchRange.lowerBound < end {
  30. guard let range = range(
  31. of: substring,
  32. options: options,
  33. range: searchRange,
  34. locale: locale
  35. )
  36. else { break }
  37. ranges.append(range)
  38. let shiftedStart = index(range.lowerBound, offsetBy: 1)
  39. searchRange = shiftedStart ..< end
  40. }
  41. return ranges
  42. }
  43. }