swift中獲取字符串前綴的七種方法總結(jié)
我們以為 "Hello World"
這個字符串為例,判斷是否以 Hello 開頭。
1. 使用 hasPrefix(_:) 方法
可以使用字符串的 hasPrefix(_:)
方法檢查字符串是否有指定的前綴:
let str = "Hello World" if str.hasPrefix("Hello") { // true print("\(str) 以 Hello 開頭") }
這個方法直接返回一個 Bool
來判斷是否以某個字符串開頭。
2. prefix 函數(shù)獲取前綴子字符串
可以使用 prefix(_:)
來獲取前綴子字符串:
let str = "Hello World" let prefix = str.prefix(5) if prefix == "Hello" { print("\(str) 以 Hello 開頭") }
這種方法利用 prefix
函數(shù)獲取前 5 個字符,然后再與 "Hello" 做對比。
3. prefix(upTo:) 函數(shù)獲取前綴子字符串
可以使用 prefix(upTo:)
來獲取前綴子字符串:
let str = "Hello World" let index = str.index(str.startIndex, offsetBy: 5) let prefix = str.prefix(upTo: index) if prefix == "Hello" { print("\(str) 以 Hello 開頭") }
這種方法先利用 index(_:, offsetBy:)
獲取前五個字符的下標(biāo),然后利用 prefix(upTo:)
函數(shù)獲取前 5 個字符,最后與 "Hello" 做對比的方式,適用于獲取字符串前 n 個字符的情況。
4. 使用字符串區(qū)間索引
先獲取前 5 個字符的下標(biāo),再根據(jù)下標(biāo)區(qū)間獲取前 5 個字符的值,最后再與對應(yīng)的字符串對比:
let str = "Hello World" let index = str.index(str.startIndex, offsetBy: 5) let prefix = str[..<index] if prefix == "Hello" { print("\(str) 以 Hello 開頭") }
5. 使用條件獲取
可以使用 prefix(while:)
獲取滿足條件的前綴:
let str = "Hello World" let prefix = str.prefix { c in !c.isWhitespace } if prefix == "Hello" { print("\(str) 以 Hello 開頭") }
這種方法利用 prefix(while:)
函數(shù)獲取指定指定條件(第一個空格之前)的字符串,再和 "Hello" 對比得出結(jié)果。
6. 使用 firstIndex/lastIndex
可以結(jié)合 firstIndex(of:)
或 lastIndex(of:)
獲取特定字符的索引,從而獲取前綴:
let str = "Hello World" if let end = str.firstIndex(of: " "), str[..<end] == "Hello" { print("\(str) 以 Hello 開頭") }
先用 firstIndex(of:)
方法獲取到第一個空格所在的位置,再根據(jù)下標(biāo)區(qū)間獲取指定的前綴。
7. 使用 prefix(through:) 函數(shù)
prefix(through:)
可以獲得從開頭到指定位置的子集合,跟上邊第二種方法差不多,只不過這里的參數(shù)傳的是下標(biāo)類型:
let str = "Hello World" let index = str.index(str.startIndex, offsetBy: 4) let prefix = str.prefix(through: index) if prefix == "Hello" { print("\(str) 以 Hello 開頭") }
以上就是獲取字符串前綴的 7 種常用方法,可以根據(jù)需要選擇最適合的方式。
以上就是swift中獲取字符串前綴的七種方法總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于swift獲取字符串前綴的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
因為一個Crash引發(fā)對Swift構(gòu)造器的思考分析
這篇文章主要給大家介紹了關(guān)于因為一個Crash引發(fā)對Swift構(gòu)造器的思考分析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者使用Swift具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10Objective-c代碼如何移植為Swift代碼 Objective-c代碼轉(zhuǎn)移到Swift過程介紹
這篇文章主要介紹了Objective-c代碼如何移植為Swift代碼,Objective-c代碼轉(zhuǎn)移到Swift過程介紹,需要的朋友可以參考下2014-07-07Swift編程中用以管理內(nèi)存的自動引用計數(shù)詳解
這篇文章主要介紹了Swift編程中用以管理內(nèi)存的自動引用計數(shù)詳解,是Swift入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-11-11Swift使用transform 實現(xiàn)重復(fù)平移動畫效果
這篇文章主要介紹了Swift使用transform 實現(xiàn)重復(fù)平移動畫效果,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-07-07Swift中實現(xiàn)點擊、雙擊、捏、旋轉(zhuǎn)、拖動、劃動、長按手勢的類和方法介紹
這篇文章主要介紹了Swift中實現(xiàn)點擊、雙擊、捏、旋轉(zhuǎn)、拖動、劃動、長按手勢的類和方法介紹,本文分別給出了各種手勢的實現(xiàn)代碼,需要的朋友可以參考下2015-01-01