本文为OC开发者转swift时,遇到的各种小白问题,贻笑大方,仅为个人学习历程。
- 字符串创建:
OC:NSString *str = @"";
swift:let str = ""
swift中,let为常量参数,str以此修饰,申请后不可修改值。如后续要修改,要用var。
- 字符串替换:
1、全部替换某个字符串
OC:str = [str stringByReplacingOccurrencesOfString:@"-" withString:@"*"];
swift:str = str.replacingOccurrences(of: "-", with: "*")
2、找到某个字符串最后出现的位置,并替换
OC:
NSString *str = @"123-312-231";
NSRange range = [str rangeOfString:@"-" options:NSBackwardsSearch];
if (range.location != NSNotFound) {
str = [str stringByReplacingCharactersInRange:range withString:@"*"];
}
swift:
var str = "123-312-231"
let position = str.range(of: "-", options: .backwards, range: str.index(str.startIndex, offsetBy: 0)..<str.index(str.endIndex, offsetBy: 0), locale: nil)
if !(position?.isEmpty ?? true) {
let pos = str.distance(from: str.startIndex, to: (position?.lowerBound)!)
str = str.replacingOccurrences(of: "-", with: "*", options: .backwards, range: str.index(str.startIndex, offsetBy: pos)..<str.endIndex)
}
- 字符串分割、拼接
OC:
NSString *str = @"123-312-231";
NSArray *array = [str componentsSeparatedByString:@"-"];//@[@"123",@"312",@"231"]
str = [array componentsJoinedByString:@"*"];//@"123*312*231"
str = [str stringByAppendingString:@"##"];//@"123*312*231##"
swift:
var str = "123-312-231"
let array:Array = str.components(separatedBy: "-")//@[@"123",@"312",@"231"]
str = array.joined(separator: "*")//"123*312*231"
- 字符串截取
OC:
NSString *subStr = [str substringWithRange:NSMakeRange(0, 4)];//@"123-"
subStr = [str substringFromIndex:4];//@"312-231"
subStr = [str substringToIndex:3];//@"123"
swift:
var str = "123-312-231"
var subStr = str.prefix(4)//"123-"
subStr = str.suffix(4)//"-231"
subStr = str[str.index(str.startIndex, offsetBy: 2)..<str.index(str.startIndex, offsetBy: 5)]//"3-3"
- 字符串删除、插入、添加
OC:
NSMutableString *str = @"123-312-231".mutableCopy;
[str deleteCharactersInRange:NSMakeRange(3, 1)];//@"123312-231"
[str insertString:@"*" atIndex:3];//@"123*312-231"
[str appendString:@"##"];//@"123*312-231##"
[str appendFormat:@"%@",@"$$"];//@"123*312-231##$$"
swift:
var str = "123-312-231"
str.remove(at: str.index(str.startIndex, offsetBy: 3))//"123312-231"
str.insert(contentsOf: "*", at: str.index(str.startIndex, offsetBy: 3))//"123*312-231"
str.append("##")//"123*312-231##"
str.append(contentsOf: "$$")//"123*312-231##$$"