-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathString.swift
138 lines (87 loc) · 3.23 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
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
//
// String.swift
// SwiftStructures
//
// Created by Wayne Bishop on 7/1/16.
// Copyright © 2016 Arbutus Software Inc. All rights reserved.
//
import Foundation
extension String: Keyable {
//hash table requirement
var keystring: String {
return self
}
//compute the length
var length: Int {
return self.count
}
//determine if all characters are unique
func isStringUnique() -> Bool {
//evaluate trival case
guard self.count < 128 else {
return false
}
//match unicode representation - O(n)
var list = Array<Bool?>(repeatElement(nil, count: 128))
for scalar in self.unicodeScalars {
let unicode = Int(scalar.value)
if list[unicode] != nil {
return false
}
list[unicode] = true
}
return true
}
//formats a string to date format
var datevalue: Date! {
let stringFormatter = DateFormatter()
stringFormatter.dateFormat = "MM-dd-yyyy"
stringFormatter.locale = Locale(identifier: "en_US_POSIX")
//check for correct date format
if let d = stringFormatter.date(from: self) {
return Date(timeInterval: 0, since: d)
}
else {
return nil
}
}
//returns characters up to a specified integer
func substring(to: Int) -> String {
//define the range
let range = self.index(self.startIndex, offsetBy: to)
//return self.substring(to: range) - Swift 3.0
return String(self[..<range])
}
//replace string content
func replace(element:String, replacement:String) -> String {
return self.replacingOccurrences(of: element, with: replacement)
}
//removes empty string content
func removingWhitespace() -> String {
return self.replace(element: " ", replacement: "")
}
//create a unique identifer based on date
func identifierWithDate(date: Date) -> String {
let cleartext = self + String(describing: date)
return String(cleartext.hashValue)
}
//reverse string order
func reverse() -> String {
/*
notes: While this operation would normally be done with the
native characters.reversed() method, this has been added as an example interview question.
*/
//convert to array
var characters = Array(self)
var findex: Int = characters.startIndex
var bindex: Int = characters.endIndex - 1
while findex < bindex {
//swap(&characters[findex], &characters[bindex]) - Swift 3.0
characters.swapAt(findex, bindex)
//update values
findex += 1
bindex -= 1
} //end while
return String(characters)
}
}