Skip to content

Commit aac74d1

Browse files
author
Matthew Judy
committed
Add String extensions.
1 parent b72247f commit aac74d1

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Sources/Shared/String+.swift

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
//
2+
// String+.swift
3+
//
4+
// Created by Matthew Judy on 12/4/23.
5+
//
6+
7+
import Foundation
8+
9+
10+
extension StringProtocol
11+
{
12+
public func ranges<T: StringProtocol>(of string: T, options: String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil, locale: Locale? = nil) -> [Range<Self.Index>]
13+
{
14+
var ranges = Array<Range<Index>>()
15+
var startIndex = searchRange?.lowerBound ?? self.startIndex
16+
let endIndex = searchRange?.upperBound ?? self.index(before:self.endIndex)
17+
18+
while (startIndex < endIndex),
19+
let range = self[startIndex...endIndex].range(of: string, options: options, locale: locale)
20+
{
21+
ranges.append(range)
22+
startIndex = if (range.lowerBound < range.upperBound) { range.upperBound }
23+
else { index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex }
24+
}
25+
26+
return ranges
27+
}
28+
29+
30+
public func indices<T: StringProtocol>(of string: T, options: String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil, locale: Locale? = nil) -> [Self.Index]
31+
{
32+
self.ranges(of: string, options: options, range: searchRange, locale: locale).map(\.lowerBound)
33+
}
34+
35+
36+
public func index<T: StringProtocol>(of string: T, options: String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil, locale: Locale? = nil) -> Index?
37+
{
38+
self.range(of: string, options: options, range: searchRange, locale: locale)?.lowerBound
39+
}
40+
41+
42+
public func endIndex<T: StringProtocol>(of string: T, options: String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil, locale: Locale? = nil) -> Index?
43+
{
44+
self.range(of: string, options: options, range: searchRange, locale: locale)?.upperBound
45+
}
46+
}
47+
48+
49+
50+
extension String
51+
{
52+
public var integers: [Int]
53+
{
54+
self.compactMap { Int(String($0)) }
55+
}
56+
57+
58+
public func applying(replacements: [(searchString: String, replacement: String)]) -> String
59+
{
60+
replacements.reduce(self) { $0.replacingOccurrences(of: $1.0, with: $1.1) }
61+
}
62+
}
63+
64+

0 commit comments

Comments
 (0)