OC转swift-字符串

本文为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##$$"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值