Swift 字符串常用的方法

1.字符串拼接

        var a = "1"
        a.append("2")
        a += "3"
        a+"4"
        print(a)
        //输出结果:123

本人亲测 a+"4"这个方法,打印后输出结果为123,一直不明白是怎么回事,有明白的大神可以给我留言

2.字符串大小写转换

        let cafe = "BBQ Café ?"
        print(cafe.lowercased())
        //输出 bbq café ?
        print(cafe.uppercased())
        //输出BBQ CAFÉ ?

3.判断字符串是否为空

        let hello = String()
        print(hello.isEmpty)
        //输出 true
        let world = "world"
        print(world.isEmpty)
        //输出 false

4.是否包含前缀后后缀

        let hasFix = "www.baidu.com"
        print(hasFix.hasPrefix("www."))
        //输出 true
        print(hasFix.hasSuffix(".com"))
        //输出 true

5.字符串替换

        let str = "2018.08.08"
        print(str.replacingOccurrences(of: ".", with: "-"))
        //输出 2018-08-08

6.字符串插入

需求:20180808  显示为:2018年08月08日  代码如下:

//将此方法放到你的工具类中,可全局调用
    public func stringInsertData(str: String) -> String {
        //声明一个可变字符串
        var newStr = str
        //插入数据 str.startIndex->起始index  offsetBy偏移量
        newStr.insert("年", at: str.index(str.startIndex, offsetBy: 4))
        newStr.insert("月", at: str.index(str.startIndex, offsetBy: 7))
        newStr.insert("日", at: str.index(newStr.endIndex, offsetBy: 0))
        return newStr
    }

7.字符串移除

        var str = "20180808"
        print(str.remove(at: str.startIndex))
        //输出 2
        str.removeAll()

8.字符串比较大小

        let a = "1"
        let b = "2"
        let c = max(a, b)
        let d = "3"
        //此处可以输入任意个数进行比较
        print(max(a, b, c, d))
        //输出3
        print(min(a, b, c, d))
        //输出1


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值