一、字符串简介
- 是一个结构体,结构体的性能更高;
- String 支持直接遍历;
- Swift 提供了 NSString 和 String 的无缝对接;
- 字符串在 OC 中的格式为:@" ",在 Swift 中的格式为:" "。
二、字符串定义
//不可变字符串
let a = "123"
//可变字符串
var b = "456"
b = "666"
三、字符串的长度
//字符串长度
let aa = "123a旺旺"
//按字节的长度,一个汉字占三个字节
aa.lengthOfBytes(using: String.Encoding.utf8) //10
//按字符个数
aa.characters.count //6
//aa.characters 可当数组使用
for i in aa.characters {
print(i)
}
四、字符串的拼接
let aa = "123a旺旺"
let bb = "xyz"
bb + aa //"xyz123a旺旺"
let cc = 123
bb + "\(cc)" //"xyz123"
五、字符串格式化
let dd = 144
let ddd = String(format: "%02d:%02d", dd/60, dd%60) //"02:24"
六、字符串的截取
let ee = "Hello,World"
let startI = ee.startIndex
let secondI = ee.index(after: startI)
ee.substring(from: secondI) //"ello,World"
ee //"Hello,World"
let endI = ee.endIndex
let middleI = ee.index(endI, offsetBy: -6)
ee.substring(to: middleI) //"Hello"
let range:Range<String.Index> = startI..<middleI
ee.substring(with: range) //"Hello"
ee.substring(with: secondI..<endI) //"ello,World"
ee //"Hello,World"
七、字符串的替换
var ff = "World,Hello"
let sIndex = ff.startIndex
let mIndex = ff.index(sIndex, offsetBy: 5)
let range2 = sIndex...mIndex
ff.replaceSubrange(range2, with: "123") //"123Hello"
ff //"123Hello"