初始化空字符串
var emptyString = ""
var anotherEmptyString = String()
字符串可变性
var variableString = "horse"
variableString += "and carriage"
通过Boolean 类型的isEmpty 属性来判断该字符串是否为空
if emptyString.isEmpty{
println("sds");
}
let contantSring = "Highlander"
contantString += "and sds"; //报错 ,常量不可以被修改
for character in "Dog!????"{
}
let yenSign:Character = “a”
通过调用全局 countElements 函数,并将字符串作为参数进行传递可以获取该字符串的字符数量。
- let unusualMenagerie = "Koala ????, Snail ????, Penguin ????, Dromedary ????"
- println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
- prints "unusualMenagerie has 40 characters"
字符串插值
字符串插值是一种全新的构建字符串的方式,可以在其中包含常量、变量、字面量和表达式。
您插入的字符串字面量的每一项都被包裹在以反斜线为前缀的圆括号中:
let str = 3
let message = "\(str) times 2.5 is \(double(str) * 2.5)
"
message is "3 times 2.5 is 7.5"
在上面的例子中,multiplier 作为 \(multiplier) 被插入到一个字符串字面量中。
当创建字符串执行插值计算时此占位符会被替换为 multiplier 实际的值。
注意:您插值字符串中写在括号中的表达式不能包含非转义双引号 (") 和反斜杠 (\),并且不能包含回车或换行符。 |
比较字符串:
Swift 提供了三种方式来比较字符串的值: 字符串相等,前缀相等和后缀相等
字符串相等
如果两个字符串以同一顺序包含完全相同的字符,则认为两者字符串相等:
- let quotation = "We're a lot alike, you and I."
- let sameQuotation = "We're a lot alike, you and I."
- if quotation == sameQuotation {
- println("These two strings are considered equal")
- }
- // prints "These two strings are considered equal"
通过调用字符串的 hasPrefix/hasSuffix 方法来检查字符串是否拥有特定前缀/后缀。两个方法均需要以字符串作为参数传入并返回 Boolean 值。
两个方法均执行基本字符串和前缀/后缀字符串之间逐个字符的比较操作。
- let romeoAndJuliet = [
- "Act 1 Scene 1: Verona, A public place",
- "Act 1 Scene 2: Capulet's mansion",
- "Act 1 Scene 3: A room in Capulet's mansion",
- "Act 1 Scene 4: A street outside Capulet's mansion",
- "Act 1 Scene 5: The Great Hall in Capulet's mansion",
- "Act 2 Scene 1: Outside Capulet's mansion",
- "Act 2 Scene 2: Capulet's orchard",
- "Act 2 Scene 3: Outside Friar Lawrence's cell",
- "Act 2 Scene 4: A street in Verona",
- "Act 2 Scene 5: Capulet's mansion",
- "Act 2 Scene 6: Friar Lawrence's cell"
- ]
您可以利用 hasPrefix 方法使用romeoAndJuliet数组来计算话剧中第一幕的场景数:前缀
- var act1SceneCount = 0
- for scene in romeoAndJuliet {
- if scene.hasPrefix("Act 1 ") {
- ++act1SceneCount
- }
- }
- println("There are \(act1SceneCount) scenes in Act 1")
- // prints "There are 5 scenes in Act 1"
同样,可使用hasSuffix方法来计算发生在Capulet公馆和Lawrence牢房内以及周围的场景数。:后缀
- var mansionCount = 0
- var cellCount = 0
- for scene in romeoAndJuliet {
- if scene.hasSuffix("Capulet's mansion") {
- ++mansionCount
- } else if scene.hasSuffix("Friar Lawrence's cell") {
- ++cellCount
- }
- }
- println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
- // prints "6 mansion scenes; 2 cell scenes"
大写和小写字符串 uppercaseString lowercaseString
- let normal = "Could you help me, please?"
- let shouty = normal.uppercaseString
- // shouty 值为 "COULD YOU HELP ME, PLEASE?"
- let whispered = normal.lowercaseString
- // whispered 值为 "could you help me, please?"