三、Swift的字符串

1 普通字面量

// 字面量賦值
let str = ""
//  初始化器
let str1 = String()

2 多行字符串字面量

// 加入換行符, 讓換行符成為字符串的內(nèi)容
let mStr = """
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."
"""
// 使用 \ 代替換行符,換行符不會成為字符串的值
let mStr2 = """
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."
"""

3 字符串里的特殊字符

3.1轉(zhuǎn)義字符

\n \t \0 \r \n \" \' \\ 等這些轉(zhuǎn)義字符

3.2 Unicode標(biāo)量 \u{n},n是一個(gè)1-8位的16進(jìn)制數(shù)字,其值是合法的Unicode

3.3 多行字符串字面量包含雙引號不需要轉(zhuǎn)義,如果包含"""三引號需要轉(zhuǎn)義

let uuu = "\u{2a5d}"

4 擴(kuò)展字符串分隔符(Raw String)

Swift5新增的特性
會忽略字符串里的特殊字符;
如果想讓字符串里的某個(gè)特殊字符生效,可以加和首尾同等數(shù)量的#

let str = "Line 1\nLine 2" // 這個(gè)會輸出倆行, 
let str2 = #"Line 1\nLine 2"# // 會輸出Line 1\nLine 2
let str3 = #"Line 1\#nLine 2"# // 這個(gè)也會輸出倆行 
let str4 = ##"Line"# 1\nLine\### 2"## // 遇到"#首尾加不等數(shù)的#

字符串常見操作

var 指定可以修改 let不可以修改 ,類似于oc里的NSStringNSMutableString

var varStr = "var string" varStr += " hello"是可以修改的

字符串是值類型

String傳遞給方法或者函數(shù)的時(shí)候會被復(fù)制過去
賦值給常量或者變量
Swift編譯器優(yōu)化了字符串使用的資源, 實(shí)際上拷貝只會在需要的時(shí)候才進(jìn)行

let welcome = "hello"
var welcome1 = welcome

print(welcome == welcome1) // true
welcome1.append(",") 
print(welcome) // hello
print(welcome1) // hello,

welcome1的更改并不會影響welcome

操作字符

每個(gè)字符的類型都是Character

  1. for-in
  2. 索引
let newStr = "abcdefg世界"

for c in newStr {
    print(c)
}

字符串拼接

  1. + 創(chuàng)建新字符串
    "hello "+"world"
  2. +=在已經(jīng)存在的String的末尾追加一個(gè)String
    let str = "Hellow" str+=" World"
  3. 使用Stringappend()方法給字符串變量末尾追加Character

字符串插值

字符串插值是一種從混合常量、變量、字面量和表達(dá)式的字符串字面量構(gòu)造新String值的方法;
每一個(gè)插入到字符串字面量的元素都要被一對圓括號包裹, 然后用反斜杠前綴
類似于OC的NSString stringWithFormat方法,但更簡潔 ,強(qiáng)大
?? 字符串插值也不會在Row String里起作用,如果想在里邊起作用,在反斜杠后匹配首尾同等數(shù)量的#

// 正常插值
let str = "6 * 7 = \(6*7)"
print(str)
// Raw String
// 輸出 6 * 7 = \(6*7)
let str = "6 * 7 = \(6*7)"
print(str)
// 插值在Raw String 起作用
let str = #"6 * 7 = \#(6*7)"#
print(str)

字符串索引

每個(gè)String值都有相關(guān)的索引類型, String.Index,它 相當(dāng)于每個(gè)Character在字符串中的位置
startIndex 屬性是字符串中的第一個(gè)位置 endIndex是字符串中最后一個(gè)字符的位置, 所以endIndex不是字符串下標(biāo)腳本的合法實(shí)際參數(shù)
String為空,則startIndexendIndex相等
?? 不能用數(shù)字索引 let greeting = "guest" greeting[0] 這種是不允許的

獲取索引

  • index(before:)index(after:)方法來獲取索引的前后
  • 要訪問給定索引更遠(yuǎn)的索引,可以使用index(_:offsetBy:)
  • 使用indices屬性來訪問字符串中每個(gè)字符的的索引
let str = "Hello World"
print(str[str.startIndex]) // H
print(str[str.index(before: str.endIndex)]) // d

插入

  • 插入字符, 使用insert(_:at:)方法
  • 插入另一個(gè)字符串的內(nèi)容到特定的索引, 使用insert(contentsOf:at:)方法
var str = "Hello"
str.insert("!", at: str.endIndex)
print(str) // Hello!

str.insert(contentsOf: " World", at: str.index(before: str.endIndex))
print(str) // Hello World!

刪除

  • 移除字符 , 使用 remove(at:)方法
  • 移除一小段特定范圍的字符串 , 使用removeSubrange(_:)方法
let range = str.index(str.endIndex, offsetBy: -6)..<str.endIndex //先構(gòu)造range
str.removeSubrange(range)
print(str)

子字符串

使用下標(biāo)或者類似的prefix(_:)的方法得到的子字符串是Substring類型
Substring 擁有String大部分方法
Substring可以轉(zhuǎn)成String類型

為什么要單獨(dú)出一個(gè)Substring類型呢,很大部分是為了性能考慮,

  • 子字符串可以重用一部分原字符串的內(nèi)存
  • 修改字符串或者子字符串之前都不需要花費(fèi)拷貝內(nèi)存的代價(jià)
  • SubstringString都遵循StringProtocol協(xié)議, 也就是說基本上都很方便的兼容所有接受StringProtocol值的字符串操作函數(shù)
var str = "Hello, world"
let index = str.firstIndex(of: ",") ?? str.endIndex
let subString = str[..<index] //使用區(qū)間運(yùn)算符
print(subString) // Hello 類型是Substring

let newString = String(subString) //使用初始化器轉(zhuǎn)成String類型
print(newString)

字符串比較

  • 字符串和字符串相等性 (==!=
  • hasPrefix(_:)前綴比較
  • hasSuffix(_:)后綴比較
var str = "Hello, world"
let welcome1 = "hello"
print(welcome1 == str) // false
print(str.hasPrefix("Hello")) // true
print(str.hasSuffix("world")) //true
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容