swift学习之String常见操作
1.字符拆分(separate)
)
let currentVersion = "V1.0.6.1221" // 定义一段字符串 let strArray = currentVersion.components(separatedBy: ".") // 将字符串分离,分离点是字符串“.” print("分离的字符:\(strArray)")
运行结果:
分离的字符:["V1","0","6","1221"]
2.增加字符串内容(append)
currentVersion.append(".8086") // 增加字符串内容 print("增加内容后的字符串:\(currentVersion)")
增加内容后的字符串:V1.0.6.1221.8086
3.截取字符串内容(substring)
let cutoutString = (currentVersion as NSString).substring(with: NSRange(location: 0,length: 6)) //截取currentVersion前6位字符串 print("截取的字符串:\(cutoutString)")
运行结果:
截取的字符串:V1.0.6
4.字符串前后缀判断
// 字符串前缀和后缀判断 let httpString = "http://www.apple.com" let jpgName = "Jobs.jpg" if httpString.hasPrefix("http://") { print("这是一个网址") } if jpgName.hasSuffix(".jpg") { print("这是一张jpg图片") }
这是一个网址 这是一张jpg图片
5.数字字符串比较大小
// 数字字符串比较大小
let numberStringOne = "123"
let numberStringTwo = "456"
if numberStringOne > numberStringTwo {
print("\(numberStringOne)大于\(numberStringTwo)!")
} else if numberStringOne < numberStringTwo{
print("\(numberStringOne)小于\(numberStringTwo)!")
} else {
print("\(numberStringOne)等于\(numberStringTwo)!")
}
运行结果:
123小于456!
6.数字字符串转成整型
// 数字字符串转成整型 let numberStringThree = "1234" let number = (numberStringThree as NSString).intValue print("String转化Int结果:",number)
String转化Int结果: 1234通过设置断点,可以看出,number的类型确实转成了Int32,如图: