Swift - 字符串(String)用法详解

前端之家收集整理的这篇文章主要介绍了Swift - 字符串(String)用法详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面对String常用的属性方法做个总结

1,判断是否为空:isEmpty
var str: String = ""
if str.isEmpty{
print( "is empty" )
}

2,获取字符数量 string.characters.count
let str = "hangge.com"
"\(str.characters.count)个字符" )

3,检查字符串是否有特定前缀/后缀: hasPrefix/hasSuffix
str =str.hasSuffix(".com"){
4,还可以用“\()”在字符串里包裹变量,常量
let name =let msg ="欢迎来到 \(name)"

5,大小写转换: 通过字符串的uppercaseString、lowercaseString、capitalizedString属性来访问一个字符串的大写/小写/首字母大写
1
2
3
4
5
let str = "Welecome to hangge.com"
let uppercase = str.uppercaseString //WELECOME TO HANGGE.COM
let lowercase = str.lowercaseString //welecome to hangge.com
let capitalized = str.capitalizedString //Welecome To Hangge.Com

6,字符串截取 (1)将String转化为NSString再截取
letstr ="Welecome to hangge.com"
fromStr = (str as NSString ).substringFromIndex(5) //ome to hangge.com
toStr = (str ).substringToIndex(5) //Welec
rangeStr = (str ).substringWithRange( NSMakeRange (4,1)) //c
(2)直接调用String的对应方法(推荐)
index = str.startIndex.advancedBy(5)
index2 = str.endIndex.advancedBy(-5)
range = Range < String . Index >(start: index,end: index2)
fromStr = str.substringFromIndex(index) //ome to hangge.com
toStr = str.substringToIndex(index2) //Welecome to hangg
rangeStr = str.substringWithRange(range) //ome to hangg

猜你在找的Swift相关文章