Swift字符串简单使用

1.字符串的定义

var str1 = "hello, sk." //字符串变量
let str2 = "hello, sk." //字符串常量
let str3 = "" //空字符串
let str4 = String() //空字符串

2.字符的定义

var char1:Character = "m" //字符变量
let char2:Character = "m" //字符常量

3.字符串的连接

let str1 = "hello, "
let str2 = "sk."
let str3 = str1+str2 //=连接str1、str2
//str3 = "hello, sk."
//----------------------------------------
let str4 = "\(str1)\(str2)" //=连接str1、str2
//str4 = "hello, sk."
//----------------------------------------
let strArray = ["sk", "wyj", "sf"]
//swift 1.0
let joinStr = ",".join(strArray)
//swift 2.0
let joinStr = strArray.joinWithSeparator(",")
print(joinStr)
//打印结果 sk,wyj,sf

4.字符串与字符的连接

let char1:Character = "o"
var str1 = "hell"
let str2 = str1+String(char1)
//str2 = "hello"
//----------------------------------------
let str3 = "\(str1)\(char1)"
//str3 = "hello"
//----------------------------------------
str1.append(char1)
//str1 = "hello"

5.字符串与其它类型值的连接

let xx = 10
let yy = 10.8
let str1 = "\(xx)+\(yy)=?"
//str1 = "10+10.8=?"
//----------------------------------------
let str2 = String(format: "%i+%.1f=?", xx, yy)
//str2 = "10+10.8=?"

6.字符串枚举字符

//Swift 1.2
let str = "sunke"
for ch in str{
 println(ch)
}
//-----------------------
//Swift 2.0
let str = "sunke"
for ch in str.characters{
 print(ch)
}

你可能感兴趣的:(Swift字符串简单使用)