字符串的介绍
- 字符串在开发中使用得非常频繁
- OC和Swift中字符串的区别
- 在OC中字符串类型是
NSString
,在Swift中字符串类型是String
- OC中字符串
@""
,Swift中字符串""
- 使用 String 的原因
- String 是一个结构体,性能更高
- NSString 是一个 OC 对象,性能略差
- String 支持直接遍历
字符的定义
let str = "hello Objective-C"
var str = "hello Swift"
"""
静夜思
作者:李白
床前明月光,疑是地上霜。
举头望明月,低头思故乡。
"""
字符串的常用操作
let str = "12345678"
let len2 = str.count //8
let len3 = (str as NSString).length //8
let str1 = "abc" + "cde"
var str = "abc"
str.append("cde")
let str = "abcdefg"
for char in str {
print(char)
}
---------------------
let str = "abcdefg"
for (index, value) in str.enumerated() {
print("\(index) --- \(value)")
}
let str = "abcdefg"
print(str.lowercased()) //全部小写
print(str.uppercased()) //全部大写
let str = "abcdefg"
print(str.contains("cd")) //true
print(str.contains("c")) //true
print(str.contains("o")) //false
import Foundation
let str = "abcdefg$$aaaa$$bbbb$$ccc"
let desc = str.components(separatedBy: "$$")
for item in desc {
print(item)
}
import Foundation
let str = "abcdefg$$aaaa$$bbbb$$ccc"
let dest11 = str.replacingOccurrences(of: "$$", with: "**")
print(dest11)
let str = "Hello World"
//截取某字符串的前5个字符串
let sub1 = str.prefix(5)
//截取某字符串的后5个字符串
let str1 = str.suffix(5)
//也可以换种写法
let index2 = str.index(str.endIndex, offsetBy: -5)
let sub2 = str[index2..<str.endIndex]
//截取某字符串的第3个字符到第6个字符范围的字符串
let index3 = str.index(str.startIndex, offsetBy: 3)
let sub3 = str[str.startIndex..<index3]
let index4: String.Index = str.index(str.endIndex, offsetBy: -3)
//从某个位置开始 到某个位置结束
let sub4 = str[index3..<index4]