Swift中關於字符串的相關操作
1.字符串的大寫和小寫操作
可以通過字符串的uppercaseString和lowercaseString屬性來訪問一個字符串的大寫和小寫版本。
代碼:
let normal = "Could you help me"
let shouty = normal.uppercaseString
//shouty的值爲"COULD YOU HELP ME"
let whispered = normal.lowercaseString
//whisperd的值爲"could you help me"
2.前綴和後綴的檢索
通過調用字符串的hasPrefix和hasSuffix方法來檢查字符串是否擁有特定前綴。
代碼:
let rome = [
"Act 1 Scene 1 :niu",
"Act 1 Scene 2 :wei",
"Act 1 Scene 3 :liu",
"Act 1 Scene 4 :li",
"Act 1 Scene 5 :zhao",
"Act 1 Scene 6 :ren",
]
var act1SceneCount = 0
for scene in rome {
if scene.hasPrefix("Act 1"){
++act1SceneCount
}
}
print("There are \(act1SceneCount ) scenes in Act 1")
執行代碼後輸出:
"There are 5 scenes in Act 1"
3.字符串插值操作
代碼:
let number = 3
let Markdown = "\(number) times 2.5 is \(Double(number) * 2.5)"
//Markdown is "3 times 2.5 is 7.5"
4.字符串的+和+=操作
字符串和字符的值可以通過加法運算符“+”相加在一起,並組成一個新的字符串。
代碼:
let string1 = "hello"
let string2 = "world"
let string3 = string1+string2
//string3=helloworld
利用”+=”可以將一個字符串或者字符添加到一個已經存在的字符串變量上。
代碼:
let string4 = "!"
let string5 += string4
//string5= hello!
5.字符串的截取操作
使用substringWithRange函數進行字符串的截取操作
代碼:
let pickDate = "2004||支付成功||2016"
Nstatus1 = (pickDate as NSString).substringWithRange(NSMakeRange(6, 4))
//截取字符串從第6位開始,截取4個單位長度(該函數是從第0位開始計數的)
//Nstatus1 = 支付成功