GoodUserName
GoodUserName

Reputation: 75

Replacing Multiple Different Occurences with Multiple Different Replacements - Swift4.2

Trying to find the exact format for doing this.

I have a textField user input,

I want to take that input and find multiple occurrences and replace each unique occurrence with a different unique character respectively.

i.e. : replace "example" with "1328571"

This is my code I currently have (currently is just set up for a single replacement so it doesn't work), formatted in the way that might help to explain what I'm trying to accomplish:

        let monoText: String = textInput.text!
    
        let monoResult = monoText.replacingOccurrences(
        
            of: ["e", "x", "a", "m", "p", "l", "e"],
            with: ["1", "3", "2", "8", "5", "7"],
            

            options: NSString.CompareOptions.literal, range:nil)
    
    outputMono.text = " \(monoResult) "

I know of ways to do this in other langs like php:

$str  = $post = 'Test $asd$ lol test asd $test$';
echo preg_replace('/\$(\w+)\$/','[bb]$1[/bb]',$str);

I could just go and do an extremely long replacement set but I wanted to know if there was SOMETHING that would assist me and not make me go insane. Couldn't find anything elsewhere.

Upvotes: 1

Views: 199

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

I am still not sure if this is exactly what you are asking but if I understood correctly you can zip your collections and iterate the resulting tuples:

var result = "example"
zip(["e", "x", "a", "m", "p", "l", "e"],["1", "3", "2", "8", "5", "7"]).forEach {
    result = result.replacingOccurrences(of: $0, with: $1, options: .literal)
}
result  // 1328571

Upvotes: 1

Related Questions