删除(或替换)字符串中的某个字符
let string = "123,45 67"
//检查是否包含字符串“,”
if string.contains(","){
//删除字符串(用空""替换字符串)
let str = string.replacingOccurrences(of: ",", with: "")
print(str) //str = "12345 67"
//去除空格
str = string.replacingOccurrences(of: " ", with: "")
}
2.截取字符串
let total = "qwer"
let index = total.index(total.endIndex, offsetBy: -1)
let totalStr = total.substring(to: index)
//totalStr 输出:qwe
3.小数点后几位
let str = String(format: "%.2f", 12121.3223)
//输出:12121.32
本文介绍了如何使用Swift进行字符串的基本操作,包括删除特定字符、截取字符串以及格式化小数点后的位数。通过实例展示了如何利用Swift内置的方法来简化字符串处理任务。
1036

被折叠的 条评论
为什么被折叠?



