-
-
Notifications
You must be signed in to change notification settings - Fork 352
/
StringUtil.swift
249 lines (222 loc) · 7.99 KB
/
StringUtil.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//
// StringUtil.swift
// SwifSoup
//
// Created by Nabil Chatbi on 20/04/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* A minimal String utility class. Designed for internal SwiftSoup use only.
*/
open class StringUtil {
enum StringError: Error {
case empty
case short
case error(String)
}
// memoised padding up to 10
fileprivate static let padding: [String] = ["", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
private static let empty = ""
private static let space = " "
/**
* Join a collection of strings by a seperator
* @param strings collection of string objects
* @param sep string to place between strings
* @return joined string
*/
public static func join(_ strings: [String], sep: String) -> String {
return strings.joined(separator: sep)
}
public static func join(_ strings: Set<String>, sep: String) -> String {
return strings.joined(separator: sep)
}
public static func join(_ strings: OrderedSet<String>, sep: String) -> String {
return strings.joined(separator: sep)
}
// /**
// * Join a collection of strings by a seperator
// * @param strings iterator of string objects
// * @param sep string to place between strings
// * @return joined string
// */
// public static String join(Iterator strings, String sep) {
// if (!strings.hasNext())
// return ""
//
// String start = strings.next().toString()
// if (!strings.hasNext()) // only one, avoid builder
// return start
//
// StringBuilder sb = new StringBuilder(64).append(start)
// while (strings.hasNext()) {
// sb.append(sep)
// sb.append(strings.next())
// }
// return sb.toString()
// }
/**
* Returns space padding
* @param width amount of padding desired
* @return string of spaces * width
*/
public static func padding(_ width: Int) -> String {
if width <= 0 {
return empty
}
if width < padding.count {
return padding[width]
}
return String.init(repeating: space, count: width)
}
/**
* Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
* @param string string to test
* @return if string is blank
*/
public static func isBlank(_ string: String) -> Bool {
if (string.count == 0) {
return true
}
for chr in string {
if (!StringUtil.isWhitespace(chr)) {
return false
}
}
return true
}
/**
* Tests if a string is numeric, i.e. contains only digit characters
* @param string string to test
* @return true if only digit chars, false if empty or null or contains non-digit chrs
*/
public static func isNumeric(_ string: String) -> Bool {
if (string.count == 0) {
return false
}
for chr in string {
if !("0"..."9" ~= chr) {
return false
}
}
return true
}
/**
* Tests if a code point is "whitespace" as defined in the HTML spec.
* @param c code point to test
* @return true if code point is whitespace, false otherwise
*/
public static func isWhitespace(_ c: Character) -> Bool {
//(c == " " || c == UnicodeScalar.BackslashT || c == "\n" || (c == "\f" ) || c == "\r")
return c.isWhitespace
}
/**
* Normalise the whitespace within this string; multiple spaces collapse to a single, and all whitespace characters
* (e.g. newline, tab) convert to a simple space
* @param string content to normalise
* @return normalised string
*/
public static func normaliseWhitespace(_ string: String) -> String {
let sb: StringBuilder = StringBuilder.init()
appendNormalisedWhitespace(sb, string: string, stripLeading: false)
return sb.toString()
}
/**
* After normalizing the whitespace within a string, appends it to a string builder.
* @param accum builder to append to
* @param string string to normalize whitespace within
* @param stripLeading set to true if you wish to remove any leading whitespace
*/
public static func appendNormalisedWhitespace(_ accum: StringBuilder, string: String, stripLeading: Bool ) {
var lastWasWhite: Bool = false
var reachedNonWhite: Bool = false
for c in string {
if (isWhitespace(c)) {
if ((stripLeading && !reachedNonWhite) || lastWasWhite) {
continue
}
accum.append(" ")
lastWasWhite = true
} else {
accum.appendCodePoint(c)
lastWasWhite = false
reachedNonWhite = true
}
}
}
// open static func inSorted(_ needle: String, haystack: [String]) -> Bool {
// return binarySearch(haystack, searchItem: needle) >= 0
// }
//
// open static func binarySearch<T: Comparable>(_ inputArr: Array<T>, searchItem: T) -> Int {
// var lowerIndex = 0
// var upperIndex = inputArr.count - 1
//
// while (true) {
// let currentIndex = (lowerIndex + upperIndex)/2
// if(inputArr[currentIndex] == searchItem) {
// return currentIndex
// } else if (lowerIndex > upperIndex) {
// return -1
// } else {
// if (inputArr[currentIndex] > searchItem) {
// upperIndex = currentIndex - 1
// } else {
// lowerIndex = currentIndex + 1
// }
// }
// }
// }
/**
* Create a new absolute URL, from a provided existing absolute URL and a relative URL component.
* @param base the existing absolulte base URL
* @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)
* @return the resolved absolute URL
* @throws MalformedURLException if an error occurred generating the URL
*/
//NOTE: Not sure it work
public static func resolve(_ base: URL, relUrl: String ) -> URL? {
var base = base
if(base.pathComponents.count == 0 && base.absoluteString.last != "/" && !base.isFileURL) {
base = base.appendingPathComponent("/", isDirectory: false)
}
let u = URL(string: relUrl, relativeTo: base)
return u
}
/**
* Create a new absolute URL, from a provided existing absolute URL and a relative URL component.
* @param baseUrl the existing absolute base URL
* @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)
* @return an absolute URL if one was able to be generated, or the empty string if not
*/
public static func resolve(_ baseUrl: String, relUrl: String ) -> String {
let base = URL(string: baseUrl)
if(base == nil || base?.scheme == nil) {
let abs = URL(string: relUrl)
return abs != nil && abs?.scheme != nil ? abs!.absoluteURL.absoluteString : empty
} else {
let url = resolve(base!, relUrl: relUrl)
if(url != nil) {
let ext = url!.absoluteURL.absoluteString
return ext
}
if(base != nil && base?.scheme != nil) {
let ext = base!.absoluteString
return ext
}
return empty
}
// try {
// try {
// base = new URL(baseUrl)
// } catch (MalformedURLException e) {
// // the base is unsuitable, but the attribute/rel may be abs on its own, so try that
// URL abs = new URL(relUrl)
// return abs.toExternalForm()
// }
// return resolve(base, relUrl).toExternalForm()
// } catch (MalformedURLException e) {
// return ""
// }
}
}