定义字符串常量(常量只有读操作)
let lString = "constant"
let lString1: String = "constant"
定义字符串变量
var string = ""
var string1: String = "哈哈"
var string2 = String()
赋值
string = "this-is-a-string-variable"
字符串分割
let stringArray = string.split(separator: "-") // 按'-'分割
print(stringArray) // ["this", "is", "a", "string", "variable"]
字符串截取
let start = string.startIndex // 开始下标
let end = string.index(string.startIndex, offsetBy: 7) // 结束下标
let subString = string[start ..< end]
print(subString) // this-is
1、string.startIndex 表示第一个字符的下标
2、string.endIndex 表示最后一个字符的下标
3、startIndex、endIndex是Index类型,不是Int类型
字符串拼接
string += "!" // 追加'!'
print(string) // this-is-a-string-variable!
string += string1 // 追加字符串变量string1
print(string) // this-is-a-string-variable!哈哈
let num = 100
string = string + "--\(num)"
print(string) // this-is-a-string-variable!哈哈--100
还不快抢沙发