extension String{
//子串
func subStringFromIndex(_index:Int)->String?{
if valideIndex(index) {
let idx =self.index(startIndex, offsetBy: index)
let str =String(self[idx...])
return str
}
return nil
}
//子串
func subStringToIndex(_index:Int)->String?{
ifvalideIndex(index) {
letidx =self.index(startIndex, offsetBy: index)
letstr =String(self[..<idx])
returnstr
}
returnnil
}
//子串
func subStringWith(startIdx:Int,endIdx:Int)->String?{
if valideIndex(startIdx)&&
valideIndex(endIdx)&&
startIdx<=endIdx {
let idx1 =self.index(startIndex, offsetBy: startIdx)
let idx2 =self.index(startIndex, offsetBy: endIdx)
let str =String(self[idx1..<idx2])
return str
}
return nil
}
//插入字符串
mutating func insertWith(str:String,atIndex:Int){
//空串或索引位置不在0...count之间
if str.isEmpty||
atIndex<startIndex.utf16Offset(in:self)||
atIndex>endIndex.utf16Offset(in:self) {
}else{
self.insert(contentsOf: str, at:self.index(self.startIndex, offsetBy: atIndex))
}
}
//删除字符
mutating func removeCharacter(at:Int)->Character?{
if at < startIndex.utf16Offset(in:self) ||
at>=endIndex.utf16Offset(in:self){
returnnil
}else{
let c =self.remove(at:self.index(self.startIndex, offsetBy: at))
return c
}
}
//删除字符串
mutating func removeSubStr(startIdx:Int, endIdx:Int)->String?{
if valideIndex(startIdx)&&
valideIndex(endIdx)&&
startIdx<=endIdx{
let sIndex =self.index(startIndex, offsetBy: startIdx)
let eIndex =self.index(startIndex, offsetBy: endIdx)
let subStr =self.subStringWith(startIdx: startIdx, endIdx: endIdx)
let range = sIndex..<eIndex
self.removeSubrange(range)
return subStr
}else{
returnnil
}
}
func valideIndex(_index:Int)->Bool{
if index<startIndex.utf16Offset(in:self) ||
index>endIndex.utf16Offset(in:self){
return false
}else{
return true
}
}
}
网友评论