1. 字符串定义
var s = "aaaaaa"
// 两个字符串均为空并等价。
var emptyString = ""
var anotherEmptyString = String()
字符串字面量可以包含以下特殊字符:转义字符 \0
(空字符)、 \\
(反斜线)、 \t
(水平制表符)、 \n
(换行符)、 \r
(回车符)、 \"
(双引号)、 \'
(单引号)。
单字节 Unicode 标量,写成
\xnn
,其中nn
为两位十六进制数。双字节 Unicode 标量,写成
\unnnn
,其中nnnn
为四位十六进制数。四字节 Unicode 标量,写成
\Unnnnnnnn
,其中nnnnnnnn
为八位十六进制数。
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. 字符串遍历
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.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)