1.字符串拼接
var num1 = "hello,world"
var name = "xiaoming"
var age = 18
let student = num1 + name
let info = name + String(age)
print(name + "\(age)")
2.字符串判断与比较
1⃣️.判断是否为空
var string1 = " "
if string1.isEmpty {
print("empty")
}else{
print("NO")
} // 打印结果:empty
2⃣️.比较是否相等
var string1 = "mingtianhenhao"
var string2 = "mingtianhenhao"
if string1 ==string2{
print("相等")
}else{
print("不相等")
} //打印结果:相等
3⃣️.hasPrefix 和 hasSuffix
① hasPrefix 是否以某一个字符开头
if string1.hasPrefix("m"){ .... }else{....}
② hasSuffix 是否以某一个字符结尾
if string1.hasSuffix("o"){.....}else{ .... }
3.字符串遍历
var str = "hello,world"
str.characters.count // 字符串的字符数(个数)
for i in str.characters {
print (i)
}
4.字符串的截取
1⃣️.将String转化为NSString 利用OC的方法截取
let result = (str as NSString).substringWithRange(NSMakeRange(2,3))
//....打印结果 :llo
2⃣️.利用Swift 的Range 进行截取
①获取range
// 打印:2 表示从左向右 0.1.2-> 从2开始 包含2
let start = str.startIndex.advanceBy(2)
// 打印从右向左 0.9.8.7-> 从0开始 包含-1
let end = str.endIndex.advanceBy (-1)
let range = Range<string.index>(statr:start,end:end)
②截取
// 打印:llo,worl
let loc = str.subStringWithRange(range)
//打印:llo,world 包含2
let statrloc = str.subStringFormIndex(statr)
//打印 hello,worl end的位置在字母d 那里.
let endloc = str.subStringToIndex(end)