let quotation = """ The White Rabbit put on his spectacles. "Where shall I begin, please your Majesty?" he asked. "Begin at the beginning," the King said gravely, "and go on till you come to the end; then stop." """
初始化空字符串
1 2 3
var emptyString = ""// 空字符串字面量 var emptyString2 = String() // 字符串初始化方法 // 两个字符串均为空并等价。
字符串判空
1 2 3
if emptyString.isEmpty { print("Nothing to see here") }
字符串可变性
1 2 3 4 5 6 7
var variableString = "Horse" variableString += " and carriage" // variableString 现在为 "Horse and carriage"
let constantString = "Highlander" constantString += " and another Highlander" // 这报告一个编译错误(compile-time error) - 常量字符串不可以被修改
遍历字符串中的字符
方法1:通过for in遍历字符串中全部的字符
1 2 3
for character in"ABCDE" { print(character) }
方法2:使用 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符。
1 2 3 4 5
let greeting = "Helo, World!" for index in greeting.indices { print("\(greeting[index]) ", terminator: "") } // 控制台输出:H e l o , W o r l d !
通过字符数组初始化字符串
1 2 3
let catCharacters: [Character] = ["C", "h", "a", "r"] let catString = String(catCharacters) print(catString)
字符串连接
字符串可以通过加法运算符” + “相加在一起,创建一个新的字符串
1 2 3 4
let string1 = "hello" let string2 = " there" var welcom = string1 + string2 print(welcom)
字符串末尾追加字符
1 2
let exclamationMark: Character = "!" welcom.append(exclamationMark)
字符串插值
1 2 3
let multiplier = 3 let message = "\(multiplier) * 2.5 is \(Double(multiplier) * 2.5)" print(message)
let greeting = "Hello, world!" let index = greeting.firstIndex(of: ",") ?? greeting.endIndex let beginning = greeting[..<index] // beginning 的值为 "Hello"
// 把结果转化为 String 以便长期存储。 let newString = String(beginning)
字符串相等
Swift提供了三种方式来比较文本值:字符串字符相等、前缀相等和后缀相等。
字符串/字符相等
字符串/字符可以用等于操作符(==)和不等于操作符(!=)。
1 2 3 4 5 6 7 8 9 10 11 12 13
var quotation1 = String("this is a test string") var quotation2 = String("this is a test string") var ptr1 = withUnsafePointer(to: "ation1) { $0 } var ptr2 = withUnsafePointer(to: "ation2) { $0 } print("quotation1地址:", ptr1) print("quotation2地址:", ptr2) if quotation1 == quotation2 { print("quotation1 == quotation2") } // 控制台打印消息 // quotation1地址: 0x0000000102b1e090 // quotation2地址: 0x0000000102b1e0a0 // quotation1 == quotation2