字符串初始化:
var emptyString = "" //
空字符串字面量
var anotherEmptyString = String() //
初始化
String
实例
//
两个字符串均为空并等价。
字符串判空:
if emptyString.isEmpty {
println("
什么都没有
")
}
// 打印输出:"什么都没有"
字符串编辑
var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"
注:在oc中字符串的修改只能通过NSString和
NSMutableString来定义字符串是否可变,在swift中可以通过定义ver和let来规定字符串是否可编辑。
字符串遍历
for character in "Dog!
" { println(character)
} // D // o // g // ! //可直接通过for in遍历字符串中的字符
字符初始化
let yenSign: Character = "¥"
字符串中字符数量
方法
countElements
let unusualMenagerie = "Koala
, Snail
, Penguin
, Dromedary
" println("unusualMenagerie has \(countElements(unusualMenager
ie)) characters")
// 打印输出:"unusualMenagerie has 40 characters"
注:此处遍历得出的字符串中的数量并不一定与oc中NSString中的length相等。因为
NSString的 length 属性是基于利用 UTF-16 表示的十六位代码单元数字,而不是基于 Unicode
字符。
swift中的
utf16count与oc中的length表达一样的意思。
字符串与字符的连接
1.通过+号
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
let character2: Character = "?"
let stringPlusCharacter = string1 + character1
//
等于
"hello!"
let stringPlusString = string1 + string2
//
等于
"hello th
ere"
let characterPlusString = character1 + string1
//
等于
"!hello"
let characterPlusCharacter = character1 + character2 //
等于
"!?"
2.通过+=号
var instruction = "look over"
instruction += string2 // instruction
现在等于
"look over there" var welcome = "good morning"
welcome += character1 // welcome 现在等于 "good morning!"
注:不能将字符或字符串添加到一个已存在的字符变量上,因为一个字符变量只能包含一个字符
字符串的插值
let multiplier = 3
let message = "\(multiplier) 乘以 2.5 是 \(Double(multiplier) * 2.5)"
// message
是
"3
乘以
2.5
是
7.5"
注:括号内不能含有非转义双引号 (") 和反斜杠 (\),并且不能包含回车或换行符。
字符串比较
1.字符串相等
let quotation = "
我们是一样一样滴
."
let sameQuotation = "
我们是一样一样滴
." if quotation == sameQuotation {
println("
这两个字符串被认为是相同的
") }//
打印输出:
"
这两个字符串被认为是相同的
"
2.前缀/后缀相等
前缀:string.hasprefix(“")
后缀:string.hassuffix(“")
let romeoAndJuliet = ["Act 1 Scene 1:Verona","A public place","Act 1 Scene 2: Capulet's mansion","Act 2 Scene 6: Friar Lawrence's cell"]
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") { ++act1SceneCount }
}
var cell = 0
for scenne1 in romeoAndJuliet{
if scenne1.hasSuffix("cell")
{ cell++}
}
print("There are \(act1SceneCount) scenes in Act 1")
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") { ++act1SceneCount }
}
var cell = 0
for scenne1 in romeoAndJuliet{
if scenne1.hasSuffix("cell")
{ cell++}
}
print("There are \(act1SceneCount) scenes in Act 1")
print("There are \(cell) scenes in cell")
大小写字符串
大写:string.
uppercaseString
小写:
string.
lowercaseString