1. 字符串定義數組
var s = "aaaaaa"spa
// 兩個字符串均爲空並等價。 var emptyString = "" var anotherEmptyString = String()
字符串字面量能夠包含如下特殊字符:轉義字符 \0
(空字符)、 \\
(反斜線)、 \t
(水平製表符)、 \n
(換行符)、 \r
(回車符)、 \"
(雙引號)、 \'
(單引號)。 code
單字節 Unicode 標量,寫成 \xnn
,其中 nn
爲兩位十六進制數。 component
雙字節 Unicode 標量,寫成 \unnnn
,其中 nnnn
爲四位十六進制數。 orm
四字節 Unicode 標量,寫成 \Unnnnnnnn
,其中 nnnnnnnn
爲八位十六進制數。 ci
2. 字符串拼接字符串
//字符串拼接 var x = "x" var y = "y" var z = x + y var m = z + "m" var n = "n"n += m//使用\()完成字符串的插值 var result = "\(x)==\(y)==\(z)==\(m)==\(n)" println(result) let plus1 = s1 + c1
3. 字符串遍歷string
var myString = "This is a string" for character in myString { println(character) }
4. 字符個數統計it
var myString = "Here is my string, lets count the characters!" println(count(myString))
5. 字符串比較 & 是否包含先後綴class
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.uppercaseString let 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 = myString let data = string.dataUsingEncoding(NSUTF8StringEncoding)