Swift 6、字符串的使用
1、 OC中字符串NSString,在swift中字符串是String
2、 OC中@"",在swift中""
使用String的原因:
1.String是一个结构体,性能更高
2.NSString是一个OC对象,性能略差
3.String 支持直接遍历
4.Swift 提供了 String 和 NSString 直接的无缝连接
3、字符串的截取就是用到无缝连接,必须将String 转成 NNString 类型,“as” 方法和OC的方法一个样
Playground
import UIKit
// 1. 定义字符串
//let opration = "+"
let str = "hello world"
// 2.遍历字符串
for c in str.characters{
print(c)
}
// 3.字符串的拼接
// 3.1 两个字符串直接的拼接
let str1 = "tz"
let str2 = "hll"
//[NSString .localizedStringWithFormat(@"%@%@", str,str2)];
let str3 = str1 + str2
// 3.2 字符串和其他标识之间的拼接
let name = "what"
let age = 19
let height = 1.88
let info = "my name is \(name),my age is \(age),my height is \(height)"
// 3.3 拼接字符串时,字符串的格式化
let min = 2
let second = 8
//let timeString = "0\(min):0\(second)"
let timeString = String(format:"%02d%02d",arguments:[min,second])
//4.字符串的截取
let urlString = "www.520it.com"
// 该方法在创建 Index 是非常的麻烦 let header = urlString.characters.substringToIndex()
let header = (urlString as NSString).substring(to: 3)
let mddle = (urlString as NSString).substring(with: NSMakeRange(4, 5))
let footer = (urlString as NSString).substring(from: 10)