Skip to content

Instantly share code, notes, and snippets.

@drrost
Last active March 12, 2020 13:15
Show Gist options
  • Save drrost/54c5554ea18d9e7431dadcc1a456373b to your computer and use it in GitHub Desktop.
Save drrost/54c5554ea18d9e7431dadcc1a456373b to your computer and use it in GitHub Desktop.
extension String {
// MARK: - Substring
private func index(from: Int) -> Index {
self.index(startIndex, offsetBy: from)
}
func substring(from: Int) -> String {
let fromIndex = index(from: from)
return String(self[fromIndex...])
}
func substring(to: Int) -> String {
let toIndex = index(from: to)
return String(self[..<toIndex])
}
func substring(with r: Range<Int>) -> String {
let startIndex = index(from: r.lowerBound)
let endIndex = index(from: r.upperBound)
return String(self[startIndex..<endIndex])
}
// MARK: - Bytes
func toBytesArray() -> [UInt8] {
var bytesArray = [UInt8](repeating: 0x00, count: count)
for (i, ch) in utf8.enumerated() {
bytesArray[i] = ch
}
return bytesArray
}
// MARK: - Trimming
func trim() -> String {
trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment