一.遍历字符串
for s in str.characters {
print(s)
}
二.characters的数量
let str = “你若安好"
printf(str.characters.count) = 4
let count = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) = 12
str.utf8.count = 12
三.字符串拼接
加号拼接:let str2 = str + “便是晴天"
“\(变量名)”:print(“\(str)便是晴天")
定制字符串的拼接:
let h = 2
let m = 10
let s = 20
let strTime = String(format:”%02d:%02d:%02d”,arguments:[h,m,s]) ==> 02:23:08
四.NSString与String区别:
OC中的NSString是对象,swift中的String是结构体;
String和NSString不同,不相互兼容;
二者可以灵活转换:str as NSString转换为NSString,就任意调用OC中的方法了;
五.字符串截取:
OC方法:
let subStr = (str as NSStirng).substringWithRange(NSMakeRange())
Swift方法:
"呃呃呃饿”只是占位符,表示几个字符
letstartIndex ="呃呃呃饿".endIndex(表示4个字符)
letendIndex ="你若安好便".endIndex(表示5个字符)
//你若安好便是晴天
letswiftSubString = str2.substringWithRange(startIndex..
网友评论