-
1、初始化空字符串
let emptyString = ""
let emptyString2 = String()
-
2、遍历字符串
let string2 = "康姐是我们的好朋友!"
for a in string2.characters {
print(a)
}
-
3、获取字符串的长度
let count = string2.characters.count
print(count)
-
4、判断字符串是否为空
let emptyStr = "1"
if emptyStr.isEmpty {
print("yes")
}
-
5、字符串的拼接
let str1 = "康姐"
let str2 = "是我们的好朋友!"
let result = str1 + str2
var str3 = "haha"
str3 = str3 + str2
print(str3)
-
6、格式化字符串
let intValue = 10
let str4 = "爱情"
let str5 = "\(intValue)、因为\(str4),不会悲伤"
print(str5)
//取小数后两位
let pi = 3.1415
let str6 = String(format: "%.2f", pi)
print(str6)
-
7、字符串比较
//和C语言strcmp一样
let str7 = "a"
let str8 = "ab"
if str7 > str8 {
print(">")
} else if str7 < str8 {
print("<")
}
-
8、是否有前后缀
let str9 = "www.baidu.com"
if str9.hasPrefix("www") {
print("yes")
} else {
print("no")
}
if str9.hasSuffix("cm") {
print("yes")
} else {
print("no")
}
-
9、大小写
let str10 = str9.uppercaseString
let str11 = str9.lowercaseString
print(str10)
-
10、String转基本数据类型
let str12 = "5.2吗"
let num = Float(str12)
print(num)
-
11、截取字符串
let str13 = "康姐是我们的好朋友!"
//str13.startIndex 从0开始 Index不是int
let fromStr = str13.startIndex.advancedBy(2)
let toStr = str13.endIndex.advancedBy(-2)
let str14 = str13.substringFromIndex(toStr)
let range:Range <String.Index> = Range(start: fromStr, end: toStr)
let str15 = str13.substringWithRange(range)
print(str15)
let toStr1 = (str13 as NSString).substringToIndex(2);
print(toStr1)
let range1 = NSRange(location: 2, length: 6)
let toStr2 = (str13 as NSString).substringWithRange(range1)
print(toStr2)
请发表评论