下面对String常用的属性和方法做个总结
1,判断是否为空:isEmpty
1
2
3
|
var str: String
if str.isEmpty{
} |
2,获取字符数量:countElements
1
2
|
let str = "hangge.com"
println( "\(countElements(str))个字符" )
|
3,检查字符串是否有特定前缀/后缀:hasPrefix/hasSuffix
1
2
3
|
var str = "hangge.com"
if str.hasSuffix( ".com" ){
} |
4,还可以用“\()”在字符串里包裹变量,常量
1
2
|
let name = "hangge.com"
let msg = "欢迎来到 \(name)"
|
5,大小写转换:
通过字符串的uppercaseString、lowercaseString、capitalizedString属性来访问一个字符串的大写/小写/首字母大写
1
2
3
4
5
|
let str = "Welecome to hangge.com"
var uppercase = str.uppercaseString //WELECOME TO HANGGE.COM
var lowercase = str.lowercaseString //welecome to hangge.com
var capitalized = str.capitalizedString //Welecome To Hangge.Com
|
6,字符串截取
(1)将String转化为NSString再截取
1
2
3
4
5
|
var str = "Welecome to hangge.com"
var fromStr = (str as NSString ).substringFromIndex(5) //ome to hangge.com
var toStr = (str as NSString ).substringToIndex(5) //Welec
var rangeStr = (str as NSString ).substringWithRange( NSMakeRange (4,1)) //c
|
(2)直接调用String的对应方法(推荐)
1
2
3
4
5
6
7
8
9
|
var str = "Welecome to hangge.com"
let index = advance (str.startIndex, 5)
let index2 = advance (str.endIndex, -5)
var range = Range < String . Index >(start: index, end: index2)
var fromStr = str.substringFromIndex(index) //ome to hangge.com
var toStr = str.substringToIndex(index2) //Welecome to hangg
var rangeStr = str.substringWithRange(range) //ome to hangg
|