-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathString.swift
62 lines (51 loc) · 1.47 KB
/
String.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// String.swift
//
// Advent of Code Tools
//
import RegexBuilder
extension String {
public func trimmed() -> String {
trimmingCharacters(in: .whitespacesAndNewlines)
}
public func substring(_ start: Int, _ len: Int) -> String {
let end = index(startIndex, offsetBy: start + len)
let start = index(startIndex, offsetBy: start)
return String(self[start..<end])
}
public func indexOf(_ substr: String) -> Int? {
guard let range = self.range(of: substr) else {
return nil
}
return distance(from: startIndex, to: range.lowerBound)
}
}
// subscripts
extension String {
public subscript(_ idx: Int) -> Element {
self[index(startIndex, offsetBy: idx)]
}
public subscript(range: ClosedRange<Int>) -> String {
substring(range.lowerBound, range.upperBound - range.lowerBound + 1)
}
public subscript(range: Range<Int>) -> String {
substring(range.lowerBound, range.upperBound - range.lowerBound)
}
}
// splitting
extension String {
public var lines: [String] {
split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map { String($0) }
}
public func integers() -> [Int] {
let regex = Regex {
TryCapture {
Optionally("-")
ZeroOrMore(.digit)
} transform: {
Int($0)
}
}
return matches(of: regex).map(\.output.1)
}
}