標籤:
1. 字串定義
var s = "aaaaaa"
// 兩個字串均為空白並等價。var emptyString = "" var anotherEmptyString = String()
字串字面量可以包含以下特殊字元:逸出字元 \0
(Null 字元)、 \\
(反斜線)、 \t
(水平定位字元)、 \n
(分行符號)、 \r
(斷行符號符)、 \"
(雙引號)、 \‘
(單引號)。
單位元組 Unicode 標量,寫成 \xnn
,其中 nn
為兩位十六進位數。
雙位元組 Unicode 標量,寫成 \unnnn
,其中 nnnn
為四位十六進位數。
四位元組 Unicode 標量,寫成 \Unnnnnnnn
,其中 nnnnnnnn
為八位十六進位數。
2. 字串拼接
//字串拼接var x = "x"var y = "y"var z = x + yvar m = z + "m"var n = "n"n += m//使用\()完成字串的插值var result = "\(x)==\(y)==\(z)==\(m)==\(n)"println(result)let plus1 = s1 + c1
3. 字串遍曆
var myString = "This is a string"for character in myString{ println(character)}
4. 字元個數統計
var myString = "Here is my string, lets count the characters!"println(count(myString))
5. 字串比較 & 是否包含前尾碼
var check1:String = "Swift is good!"var check2:String = "Swift is good!"//字串是否相等if check1 == check2 { println("check1 = check2")} else { println("check1 != check2")}//是否包含首碼var preCheck = "Swift"if check1.hasPrefix(preCheck) { println("包含首碼")}//是否包含尾碼var sufCheck = "good!"if check1.hasSuffix(sufCheck) { println("包含尾碼")}
6. 大小寫轉換
let myString = "Wait a moment, please."let newString = myString.uppercaseStringlet myString = "Wait a moment, please."let newString = myString.lowercaseString
7. 字串是否包含其他字串
var myString = "This is a string test"if myString.rangeOfString("test") { println("exists")}
8. 字串截取
//截取字串的標識位從1開始計數let myString = "ABCDEFGHI"//1.從目標標識位後一個字元開始截取餘下的字串let mySubstring = (myString.substringFromIndex(2))println(mySubstring) let mySubstring2 = (myString.substringToIndex(4))println(mySubstring2)
9. 字串去空格
var myString = " Let‘s trim the whitespace " var newString = myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
10. 字串分割為字串數組
//單一分隔字元:只有一種分割符var myString = "Berlin, Paris, New York, San Francisco"//1.隱式定義字串數組var myArray = myString.componentsSeparatedByString(",")//2.顯示定義字串數組var myArray2 : String[] = myString.componentsSeparatedByString(", ")for em in myArray2 { print(em) }//多重分割符:有2個或兩個以上分隔字元var myString2 = "One-Two-Three-1 2 3"var array2:String[] = myString2.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: "- "))//["One", "Two", "Three", "1", "2", "3"]
11.字串轉換為NSData
let myString = "String to encode"let string: NSString = myStringlet data = string.dataUsingEncoding(NSUTF8StringEncoding)
swift 中String常用操作