Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extension String {
- // LEFT
- // Returns the specified number of chars from the left of the string
- // let str = "Hello"
- // print(str.left(3)) // Hel
- func left(_ to: Int) -> String {
- var t = to;
- if (t > self.count) {
- t = self.count;
- } else if (t < 0) {
- t = 0;
- }
- return "\(self[..<self.index(startIndex, offsetBy: t)])"
- }
- // RIGHT
- // Returns the specified number of chars from the right of the string
- // let str = "Hello"
- // print(str.left(3)) // llo
- func right(_ from: Int) -> String {
- var f = from;
- if (f > self.count) {
- f = self.count;
- } else if (f < 0) {
- f = 0;
- }
- return "\(self[self.index(startIndex, offsetBy: self.count-f)...])"
- }
- // MID
- // Returns the specified number of chars from the startpoint of the string
- // let str = "Hello"
- // print(str.left(2, 2)) // ll
- func mid(_ from: Int, _ count: Int = -1) -> String {
- var f = from;
- if (f < 0) {
- f = 0;
- }
- let x = "\(self[self.index(startIndex, offsetBy: f)...])"
- return x.left(count == -1 ? x.count : count)
- }
- // MIDAFTER
- // Returns the substring that are found after the specified search string
- // let str = "Hello"
- // print(str.midAfter("e")) // llo
- func midAfter(_ search : String, _ count: Int = -1) -> String {
- let r = self.range(of: search);
- if (r == nil) {
- return "";
- }
- let lb = r!.lowerBound;
- let x = "\(self[lb...])".mid(1);
- return x.left(count == -1 ? x.count : count)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement