I have to do validation to check user entered answer to an application. I want to remove spaces (if any) left or before for bellow special characters.
- /
- ,
- :
- ;
- -
- .
So the final output should be like this.
Ex:
Correct answer => a/b
Answers need to accept => ' a/b ', 'a/ b', 'a /b', 'a/ b ', 'a/b '
I can do this using replacingOccurrences function by replacing all possible values. Is there any better solution for this?
Remove before and after space of Special character using 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)
Hope it will help you. Let me know if you are still having any issue.
Happy coding.
You can using regular expression for replace the string with format [ ]+{special_char}
and {special_char}[ ]+
.
Edit
Update "."
to "\\\\."
Thanks ielyamani
For example
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
You can use replacingOccurrences
which would replace your symbol with whitespaces with just this symbol. For this purpose you can use recursive method
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
}
Usage:
let string = "Apple / Orange Swift . ObjC Moon : Sun USA - UK"
print(removed(in: string))
Apple/Orange Swift.ObjC Moon:Sun USA-UK
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.