初始化空字串
var emptystring = ""
var anotheremptystring = string()
字串可變性
var variablestring = "horse"
variablestring += "and carriage"
通過boolean 型別的isempty 屬性來判斷該字串是否為空
if emptystring.isempty
// 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陣列來計算話劇中第一幕的場景數:字首
varact1scenecount = 0
forscene
inromeoandjuliet
} println("there are \(act1scenecount) scenes in act 1"
) // prints "there are 5 scenes in act 1"
同樣,可使用hassuffix方法來計算發生在capulet公館和lawrence牢房內以及周圍的場景數。:字尾
varmansioncount = 0
varcellcount = 0
forscene
inromeoandjuliet else
ifscene.hassuffix(
"friar lawrence's cell"
) }
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?"
swift總結 字串和字元
var str hello,playground 宣告乙個字串 var emptystr 宣告乙個空的字串 var emptystr1 string 相等於上面的那個str.isempty 判斷str是不是為空false emptystr.isempty truevar str1 hello var...
swift 過濾字串 Swift 字串
swift 字串 swift 字串是一系列字元的集合。例如 hello,world 這樣的有序的字元型別的值的集合,它的資料型別為 string。建立字串 你可以通過使用字串字面量或 string 類的例項來建立乙個字串 import cocoa 使用字串字面量 var stringa hello,...
swift字串和字元
您可以在您的 中包含一段預定義的字串值作為字串字面量。字串字面量是由雙引號 包裹著的具有固定順序的文字字符集。字串字面量可以用於為常量和變數提供初始值 let somestring some string literal value 注意somestring常量通過字串字面量進行初始化,swift ...