Swift字符串的常用操作
//原始字符串
let str1 = " 我是谁 "
let str2 = str1.trimmingCharacters(in: CharacterSet.whitespaces)
//打印
print("原始字符:\(str1)")
print("新的字符:\(str2)")
//原始字符串
let str1 = "<<骆驼祥子>>"
//删除前后<>
let characterSet = CharacterSet(charactersIn: "<>")
let str2 = str1.trimmingCharacters(in: characterSet)
//打印结果
print("原字符串:\(str1)")
print("新字符串:\(str2)")
CharacterSet 里各个枚举类型的含义如下:
controlCharacters:控制符
whitespaces:空格
newlines:换行符
whitespacesAndNewlines:空格换行
decimalDigits:小数
letters:文字
lowercaseLetters:小写字母
uppercaseLetters:大写字母
nonBaseCharacters:非基础
alphanumerics:字母数字
decomposables:可分解
illegalCharacters:非法
punctuationCharacters:标点
capitalizedLetters:大写
symbols:符号
去除空格
//原始字符串
let str1 = " 我是谁 "
let str2 = str1.replacingOccurrences(of: " ", with: "")
//打印
print("原始字符:\(str1)")
print("新的字符:\(str2)")
空格替换为#
//原始字符串
let str1 = " 我是谁 "
let str2 = str1.replacingOccurrences(of: " ", with: "#")
//打印
print("原始字符:\(str1)")
print("新的字符:\(str2)")
去除所有的字母
//原始字符串
let str1:String = "qwer1234"
//判断表情的正则表达式
let pattern = "[a-zA-Z]"
//替换后的字符串
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let str2 = regex.stringByReplacingMatches(in: str1, options: [], range: NSMakeRange(0, str1.count), withTemplate: "")
//打印结果
print("原字符串:\(str1)")
print("新字符串:\(str2)")
可以把这个方法封装一下方便使用
extension String {
//使用正则表达式替换
func pregReplace(pattern: String, with: String,
options: NSRegularExpression.Options = []) -> String {
let regex = try! NSRegularExpression(pattern: pattern, options: options)
return regex.stringByReplacingMatches(in: self, options: [],
range: NSMakeRange(0, self.count),
withTemplate: with)
}
}
使用
//原始字符串
let str1:String = "qwer1234"
//判断表情的正则表达式
let pattern = "[a-zA-Z]"
//替换后的字符串
let str2 = str1.pregReplace(pattern: pattern, with: "")
//打印结果
print("原字符串:\(str1)")
print("新字符串:\(str2)")