Created
April 21, 2016 09:29
-
-
Save lynxerzhang/59a77033477045092086e14170147fa9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// StringExt.swift | |
// | |
// some useful swift string's extension | |
// | |
// Xcode version is 7.3, swift version is 2.2 | |
// | |
// TODO | |
// | |
// | |
import Foundation | |
extension String { | |
func slice(startIndex: Int = 0, endIndex: Int = Int.max) -> String { | |
var str = "" | |
var start = startIndex, end = endIndex | |
let count = self.length | |
if start < 0 { | |
if start < -count { | |
start = -count | |
} | |
start += count | |
} | |
if end < 0 { | |
end += count | |
} | |
else if end > count { | |
end = count | |
} | |
if end >= start { | |
let index = self.startIndex.advancedBy(start)..<self.startIndex.advancedBy(end) | |
str = self.substringWithRange(index) | |
} | |
return str | |
} | |
func substr(startIndex: Int = 0, len: Int = Int.max) -> String { | |
var str = "" | |
var start = startIndex, end = len | |
let count = self.length | |
if end > count { | |
end = count | |
} | |
if start < 0 { | |
if start < -count { | |
start = -count | |
} | |
start += count | |
} | |
end += start | |
if end > count { | |
end = count | |
} | |
if start < count { | |
let index = self.startIndex.advancedBy(start)..<self.startIndex.advancedBy(end) | |
str = self.substringWithRange(index) | |
} | |
return str | |
} | |
func substring(startIndex: Int = 0, endIndex: Int = Int.max) -> String { | |
var str = "" | |
var start = startIndex, end = endIndex | |
let count = self.length | |
if start < 0 { | |
start = 0 | |
} | |
if end < 0 { | |
end = 0 | |
} | |
if start > end { | |
let tmp = end | |
end = start | |
start = tmp | |
} | |
if end > count { | |
end = count | |
} | |
if start < count { | |
let index = self.startIndex.advancedBy(start)..<self.startIndex.advancedBy(end) | |
str = self.substringWithRange(index) | |
} | |
return str | |
} | |
//get string's length | |
var length: Int { | |
return self.characters.count | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment