字符串的介绍
- 字符串在任何的开发中使用都是非常频繁的
- OC和Swift中字符串的区别
- 在OC中字符串类型时NSString,在Swift中字符串类型是String
- OC中字符串@"",Swift中字符串""
- 使用
String
的原因
-
String
是一个结构体,性能更高
-
NSString
是一个 OC
对象,性能略差
-
String
支持直接遍历
-
Swift
提供了 String
和 NSString
之间的无缝转换
字符的定义
let str = "hello Objective-C"
var str = "hello Swift"
字符串的使用
获取字符串的长度
let count = str.characters.count
遍历字符串
// 字符串遍历
var str = "Hello, Swift"
for c in str.characters {
print(c)
}
字符串拼接
let str1 = "Hello"
let str2 = "World"
let str3 = str1 + str2
let name = "why"
let age = 18
let info = "my name is \(name), age is \(age)"
let min = 3
let second = 4
let time = String(format: "%02d:%02d", arguments: [min, second])
字符串的截取
- Swift中提供了特殊的截取方式
- 简单的方式是将String转成NSString来使用
let myStr = "www.520it.com"
var subStr = (myStr as NSString).substringFromIndex(4)
subStr = (myStr as NSString).substringToIndex(3)
subStr = (myStr as NSString).substringWithRange(NSRange(location: 4, length: 5))
// 1.定义字符串
let str = "www.520it.com"
// 2.截取开始位置
let fromIndex = str.startIndex.advancedBy(3)
let header = str.substringFromIndex(fromIndex)
// 3.截取结束位置
let toIndex = str.endIndex.advancedBy(-3)
let footer = str.substringToIndex(toIndex)
// 4.截取中间的字符串
let range = Range(start: str.startIndex.advancedBy(4), end: str.endIndex.advancedBy(-4))
let middle = str.substringWithRange(range)