我是靠谱客的博主 奋斗凉面,这篇文章主要介绍Swift 字符串常用的方法,现在分享给大家,希望可以做个参考。

1.字符串拼接

复制代码
1
2
3
4
5
6
7
8
var a = "1" a.append("2") a += "3" a+"4" print(a) //输出结果:123

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

2.字符串大小写转换

复制代码
1
2
3
4
5
6
let cafe = "BBQ Café ?" print(cafe.lowercased()) //输出 bbq café ? print(cafe.uppercased()) //输出BBQ CAFÉ ?

3.判断字符串是否为空

复制代码
1
2
3
4
5
6
7
let hello = String() print(hello.isEmpty) //输出 true let world = "world" print(world.isEmpty) //输出 false

4.是否包含前缀后后缀

复制代码
1
2
3
4
5
6
let hasFix = "www.baidu.com" print(hasFix.hasPrefix("www.")) //输出 true print(hasFix.hasSuffix(".com")) //输出 true

5.字符串替换

复制代码
1
2
3
4
let str = "2018.08.08" print(str.replacingOccurrences(of: ".", with: "-")) //输出 2018-08-08

6.字符串插入

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
//将此方法放到你的工具类中,可全局调用 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.字符串移除

复制代码
1
2
3
4
5
var str = "20180808" print(str.remove(at: str.startIndex)) //输出 2 str.removeAll()

8.字符串比较大小

复制代码
1
2
3
4
5
6
7
8
9
10
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


 

最后

以上就是奋斗凉面最近收集整理的关于Swift 字符串常用的方法的全部内容,更多相关Swift内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部