Swift - 字串(String)用法詳解

weixin_34126215發表於2015-09-26

下面對String常用的屬性和方法做個總結

1,判斷是否為空:isEmpty
1
2
3
var str:String
if str.isEmpty{
}


2,獲取字元數量:countElements

1
2
let str = "hangge.com"
println("\(countElements(str))個字元")


3,檢查字串是否有特定字首/字尾:hasPrefix/hasSuffix

1
2
3
var str = "hangge.com"
if str.hasSuffix(".com"){
}


4,還可以用“\()”在字串裡包裹變數,常量

1
2
let name = "hangge.com"
let msg = "歡迎來到 \(name)"


5,大小寫轉換:

通過字串的uppercaseString、lowercaseString、capitalizedString屬性來訪問一個字串的大寫/小寫/首字母大寫
1
2
3
4
5
let str = "Welecome to hangge.com"
         
var uppercase = str.uppercaseString  //WELECOME TO HANGGE.COM
var lowercase = str.lowercaseString  //welecome to hangge.com
var capitalized = str.capitalizedString  //Welecome To Hangge.Com


6,字串擷取

(1)將String轉化為NSString再擷取
1
2
3
4
5
var str = "Welecome to hangge.com"
         
var fromStr = (str as NSString).substringFromIndex(5) //ome to hangge.com
var toStr = (str as NSString).substringToIndex(5)  //Welec
var rangeStr =  (str as NSString).substringWithRange(NSMakeRange(4,1)) //c

(2)直接呼叫String的對應方法(推薦)

1
2
3
4
5
6
7
8
9
var str = "Welecome to hangge.com"
                
let index = advance(str.startIndex, 5)
let index2 = advance(str.endIndex, -5)
var range = Range<String.Index>(start: index, end: index2)
 
var fromStr = str.substringFromIndex(index)  //ome to hangge.com
var toStr = str.substringToIndex(index2)  //Welecome to hangg
var rangeStr = str.substringWithRange(range) //ome to hangg

相關文章