截取字符串在Swift中相比OC要复杂很多,主要原因可能还是OC的NSRange的创建方法中参数类型为int,而Swift却对类型要求很严格,int不能作为参数创建Range,这要使用String中的startIndex和endIndex,但问题又出来了,如果要有灵活的范围呢?在之前可以直接就用advance函数,现在的Swift没有这个函数了,要用到advancedBy和distanceTo。
以下代码是对于Range和advancedBy函数的使用:
//截取子串 let str = "Hello,Swift" let startIndex = str.startIndex //方法一:使用advancedBy + stringByReplacingCharactersInRange let endIndexA = startIndex.advancedBy(str.characters.count-1) let rangeOfHelloA = Range(start: startIndex, end: endIndexA) let newStr = str.stringByReplacingCharactersInRange(rangeOfHelloA, withString: "") print("newStr1 = " + newStr) //方法二:advancedBy + subStringWithRange let newStr2 = str.substringWithRange(rangeOfHelloA) print("newStr2 = " + newStr2) //方法三:使用NSString类型;Swift也提供了NSString和S挺 let str_OC = str as NSString let newStr3 = str_OC.substringWithRange(NSRange(location: 0, length: 5)) as String //或者 // let newStr3 = str_OC.substringWithRange(NSMakeRange(0, 5)) as String print("newStr3 = " + newStr3) //插入字符 var originStr = "0000" originStr.insert("5", atIndex: originStr.startIndex.advancedBy(2)) print("newstr4 = " + originStr) //插入字符串->字符串需要转成字符集才能进行操作 originStr.insertContentsOf("字符串".characters, at: originStr.startIndex.advancedBy(2)) print("newStr5 = " + originStr) //移除其中的某个字符 var originStr2 = "12345" originStr2.removeAtIndex(originStr2.startIndex) print("newStr6 = " + originStr2) //移除子串 注意:endIndex是从整个字符的后一位开始的,直接使用originStr2.endIndex会导致越界; let removeRange = originStr2.startIndex.advancedBy(1)...originStr2.endIndex.advancedBy(-2) originStr2.removeRange(removeRange) print("newStr7 = " + originStr2)
运行结果:
时间: 2024-10-11 21:55:34