初始化
var str = ""//字面量
var str2 = String()//初始化器语法
if str.isEmpty {
print("空字符串")
}
if str2.isEmpty {
print("空字符串")
}
字符串内换行
多行字符串用""" """
例:不需要\n换行
分隔符
print("str \n str") //换行
print(#"str1 \n str1"#)//输出\n
print(#"str1 \#n str1"#)//换行
print(###"str3 \###n str3"###)//换行,这里#跟首尾#位数有关,可以用多个位数的#,用来区分字符串内部的#
string 操作
var str = "hello"
str += " word"
print(str)// hello word
let str2 = "2 * 3 = \(2*3)"
print(str2)// 2 * 3 = 6
var str = "hello word"
print(str[str.startIndex])//字符串首字符
print(str[str.index(after: str.startIndex)])//字符串第二个字符
print(str[str.index(before: str.endIndex)])//字符串尾字符
str.insert("!", at: str.endIndex)//结尾插入!
str.insert(contentsOf: " someOne", at: str.index(before: str.endIndex))
str.remove(at: str.index(before: str.endIndex))//移除结尾!
let range = str.index(str.endIndex,offsetBy: -7)..<str.endIndex
str.removeSubrange(range)//移除字符串后面7位
字符串比较
var str = "hello word"
var str1 = "hello"
print(str.hasPrefix("hello"))//true
print(str.hasSuffix("word"))//true
print(str == str1)//false
print(str != str1)//true
subSring
var str = "hello, word, some"
let index = str.firstIndex(of: ",") str.endIndex
let index2 = str.lastIndex(of: ",") str.endIndex
let subString = str[..<index]//hello
let subString2 = str[..<index2]//hello, word
let newString = String(subString)//hello
let newString2 = String(subString2)//hello, word