swiftcharacter-replacement

What is an easier way to replace multiple characters with other characters in a string in swift?


I am currently trying to setup a string to be added to a HTTP POST request where a user would type text and tap 'enter' and a request would be sent.

I know multiple characters (^,+,<,>) can be replaced with a single character ('_') like so:

userText.replacingOccurrences(of: "[^+<>]", with: "_"

I currently am using multiple functions of:

.replacingOccurrences(of: StringProtocol, with:StringProtocol)

like so:

let addAddress = userText.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: ".", with: "%2E").replacingOccurrences(of: "-", with: "%2D").replacingOccurrences(of: "(", with: "%28").replacingOccurrences(of: ")", with: "%29").replacingOccurrences(of: ",", with: "%2C").replacingOccurrences(of: "&", with: "%26")

Is there a more efficient way of doing this?


Solution

  • I think the only problem you will run into with using addingPercentEncoding is that your question states that a space " " should be replaced with an underscore. Using addingPercentEncoding for a space " " will return %20. You should be able to combine some of these answers, define the remaining characters from your list that should return standard character replacement and get your desired outcome.

    var userText = "This has.lots-of(symbols),&stuff"
    userText = userText.replacingOccurrences(of: " ", with: "_")
    let allowedCharacterSet = (CharacterSet(charactersIn: ".-(),&").inverted)
    var newText = userText.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)
    
    print(newText!) // Returns This_has%2Elots%2Dof%28symbols%29%2C%26stuff