我必须进行验证以检查用户输入的应用程序答案。我想删除以下特殊字符的空格(如果有的话)左或之前。
- /
- ,
- :
- ;
- -
- 。
所以最终输出应该是这样的。
例如:
正确答案=> a / b
答案需要接受=>'a / b','a / b','a / b','a / b','a / b'
我可以使用replaceOccurrences函数通过替换所有可能的值来做到这一点。有更好的解决方案吗?
答案 0 :(得分:4)
使用Range
-
let specialChars = ["/",":", ",", ";", "-", "."]
let aString = " AB / CD EF ; G : H , MN O - P"
var trimmedString = aString.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars {
if let beforeSpacerange = trimmedString.range(of: " \(specialChar)") {
trimmedString.replaceSubrange(beforeSpacerange, with: specialChar)
}
if let afterSpacerange = trimmedString.range(of: "\(specialChar) ") {
trimmedString.replaceSubrange(afterSpacerange, with: specialChar)
}
}
debugPrint(trimmedString)
希望它会对您有所帮助。让我知道您是否还有任何问题。
编码愉快。
答案 1 :(得分:2)
您可以使用正则表达式将字符串替换为[ ]+{special_char}
和{special_char}[ ]+
格式。
修改
将"."
更新为"\\."
例如
func acceptedAnswer(of answer: String) -> String {
let specialChars = ["/", ":", ",", ";", "-", "\\."]
var newAnswer = answer.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars {
let beforeCharRegex = "[ ]+" + specialChar
let afterCharRegex = specialChar + "[ ]+"
newAnswer = newAnswer.replacingOccurrences(of: beforeCharRegex, with: specialChar, options: .regularExpression, range: nil)
newAnswer = newAnswer.replacingOccurrences(of: afterCharRegex, with: specialChar, options: .regularExpression, range: nil)
}
return newAnswer
}
print(acceptedAnswer(of: " apple / orange : banana "))
// apple/orange:banana
答案 2 :(得分:0)
您可以使用replacingOccurrences
,它将仅用该符号将您的符号替换为空格。为此,您可以使用递归方法
func removed(in text: String) -> String {
let symbols = ["/", ",", ":", ";", "-", "."]
var newText = text
symbols.forEach { newText = replaced(in: newText, for: $0) }
return newText
}
func replaced(in text: String, for symbol: String) -> String {
var newText = text
let left = " \(symbol)"
newText = newText.replacingOccurrences(of: left, with: symbol)
let right = "\(symbol) "
newText = newText.replacingOccurrences(of: right, with: symbol)
return newText != text ? replaced(in: newText, for: symbol) : newText
}
用法:
let string = "Apple / Orange Swift . ObjC Moon : Sun USA - UK"
print(removed(in: string))
Apple/Orange Swift.ObjC Moon:Sun USA-UK