// 类型推断
let str = "Hello"
// 指定类型
let str1 : String = "Hello"
let str1 : String = "Hello"
let str2 = "Hello"
print(str1 + "\n" + str2)
// 结果:
/**
Hello
Hello
*/
var str = "Hello"
str.append(" World")
print(str)
// 结果: Hello World
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
let str = String(format: "价格%.2f", 5.68)
// 获取长度
print(str.count)
// 结果:6
let str = "swift"
let str1 = ""
print(str.isEmpty)
// 结果:false
print(str1.isEmpty)
// 结果:true
let str = "5.68"
for char in str {
print(char)
// 结果:
/**
5
.
6
8
*/
}
let str = "this"
print(str[str.startIndex])
// 结果:t
var str = "ABC"
str.removeFirst()
// 等同于 str.remove(at: str.startIndex)
print(str)
// 结果: BC
var str = "ABCDEFGH"
str.remove(at: str.index(str.startIndex, offsetBy: 2))
print(str)
// 结果: ABDEFGH
var str = "ABC"
str.removeLast()
// 等同于str.remove(at: str.index(str.endIndex, offsetBy: -1))
print(str)
// 结果: AB
var str = "ABCDEFGH"
str.removeAll()
var str = "ABCDEFGH"
str.removeFirst(2)
str.removeLast(2)
print(str)
// 结果:CDEF
let str1 : String = "Hello"
let str = "Hello"
let str2 = "Hello world"
// 需要知道大小
let isSame = str1.compare(str2)
// 枚举 ComparisonResult -1 0 1
print(isSame.rawValue)
// 结果: -1
print(str1.compare(str).rawValue)
// 结果: 0
// 只需要知道内容是否相等
print(str1 == str)
// 结果: true
let str = "Hello"
let str1 = "Hello world"
let rec = str1.contains(str)
print(rec)
// 结果: true
let str = "Hello world"
let arr = str.split(separator: " ")
print(arr)
// 结果: ["Hello", "World"]
let arr = ["Hello", "World"]
let joined = arr.joined()
print(joined)
// 结果: HelloWorld
let sepJoined = arr.joined(separator: "----")
print(sepJoined)
// 结果: Hello----World
// 头部截取
let str = "asdfghjkl;'"
let str1 = str.prefix(2);
print(str1)
// 结果: as
// 尾部截取
let str2 = str.suffix(3);
print(str2)
// 结果: l;'
// range 截取
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
// 替换
let str = "all the world"
let str1 = str.replacingOccurrences(of: "all", with: "haha")
print(str1)
// 结果: haha the world
var str = "ABCDEFGH"
// 单个字符
str.insert("X", at:str.index(str.startIndex, offsetBy: 6))
print(str)
// 结果: ABCDEFXGH
// 多个字符
str.insert(contentsOf: "888", at: str.index(before: str.endIndex))
print(str)
// 结果: ABCDEFXG888H
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)
// 结果: ABH