① Swift 字符串创建
let str = "Hello"
let str1 : String = "Hello"
var str2 : String = "Hello"
② Swift 字符串拼接
let str1 : String = "Hello"
let str2 = "Hello"
print(str1 + "\n" + str2)
Hello
Hello
③ Swift 字符串追加
var str = "Hello"
str.append(" World")
print(str)
Hello World
④ Swift 字符串格式化
let str = String(3)
let str1 = String(5.0)
print(str, str1)
3 5.0
let str = String(format: "第%d课程", 1)
let str1 = String(format: "价格%f", 5.68)
print(str, str1)
第1课程 价格5.680000
let str2 = String(format: "价格%.2f", 5.68)
print(str2)
价格5.68
⑤ Swift 获取字符串长度
let str = String(format: "价格%.2f", 5.68)
print(str.count)
6
⑥ Swift 判断字符串是否为空
let str = "swift"
let str1 = ""
print(str.isEmpty)
false
print(str1.isEmpty)
true
⑦ Swift 遍历字符串
let str = "5.68"
for char in str {
print(char)
}
5
.
6
8
⑧ Swift 字符串操作
let str = "this"
print(str[str.startIndex])
t
var str = "ABC"
str.removeFirst()
print(str)
BC
var str = "ABCDEFGH"
str.remove(at: str.index(str.startIndex, offsetBy: 2))
print(str)
ABDEFGH
var str = "ABC"
str.removeLast()
print(str)
AB
var str = "ABCDEFGH"
str.removeAll()
var str = "ABCDEFGH"
str.removeFirst(2)
str.removeLast(2)
print(str)
CDEF
⑨ Swift 判断字符串相等
let str1 : String = "Hello"
let str = "Hello"
let str2 = "Hello world"
let isSame = str1.compare(str2)
print(isSame.rawValue)
print(str1.compare(str).rawValue)
print(str1 == str)
true
⑩ Swift 判断字符串包含另一个字符串
let str = "Hello"
let str1 = "Hello world"
let rec = str1.contains(str)
print(rec)
true
⑪ Swift 字符串分割
let str = "Hello world"
let arr = str.split(separator: " ")
print(arr)
["Hello", "World"]
⑫ Swift 数组拼接字符串
let arr = ["Hello", "World"]
let joined = arr.joined()
print(joined)
HelloWorld
let sepJoined = arr.joined(separator: "----")
print(sepJoined)
Hello----World
⑬ Swift 字符串截取
let str = "asdfghjkl;'"
let str1 = str.prefix(2);
print(str1)
as
let str2 = str.suffix(3);
print(str2)
l;'
let index3 = str.index(str.startIndex, offsetBy: 3)
let index4 = str.index(str.startIndex, offsetBy: 5)
let str5 = str[index3...index4]
print(str5)
fgh
let range = str.range(of: "jk")!
print(str[str.startIndex..<range.lowerBound])
asdfgh
print(str[str.startIndex..<range.upperBound])
asdfghjk
⑭ Swift 字符串替换
let str = "all the world"
let str1 = str.replacingOccurrences(of: "all", with: "haha")
print(str1)
⑮ Swift 字符串插入
var str = "ABCDEFGH"
str.insert("X", at:str.index(str.startIndex, offsetBy: 6))
print(str)
str.insert(contentsOf: "888", at: str.index(before: str.endIndex))
print(str)
⑯ Swift 字符串删除某段内容
var str = "ABCDEFGH"
let start = str.index(str.startIndex, offsetBy: 2)
let end = str.index(str.endIndex, offsetBy: -2)
str.removeSubrange(start...end)
print(str)