krunal nagvadia
krunal nagvadia

Reputation: 69

Replace The Multiple character with multiple Value in the String

I have to replace the All Character in the string.

For i.e var str_Ran = "ahsn45ss74d1a37adgt4t4h1fe"

Now i want to replace the Character like

str_Ran = str_Ran.replaceAll("0", "Y")
str_Ran = str_Ran.replaceAll("5", "p")
str_Ran = str_Ran.replaceAll("8", "B")
str_Ran = str_Ran.replaceAll("7", "m")
str_Ran = str_Ran.replaceAll("4", "c")
str_Ran = str_Ran.replaceAll("1", "g")
str_Ran = str_Ran.replaceAll("3", "F")
str_Ran = str_Ran.replaceAll("6", "U")
str_Ran = str_Ran.replaceAll("2", "t")

I can't find the proper way to replace the character.

Upvotes: 1

Views: 46

Answers (2)

RajeshKumar R
RajeshKumar R

Reputation: 15748

Create a dictionary will all characters which should be replaced like this. Then enumerate it and use replacingOccurrences(of:with:) method

var str_Ran: String = "ahsn45ss74d1a37adgt4t4h1fe"
var replacedStr: String {
    let dict = ["0": "Y","5": "p","8": "B","7": "m","4": "c","1": "g","3": "F","6": "U","2": "t"]
    return dict.reduce(str_Ran) { $0.replacingOccurrences(of: $1.key, with: $1.value) }
}

Upvotes: 1

Mihir Mehta
Mihir Mehta

Reputation: 13833

You can use

replacingOccurrences

method of String class for this

var str_Ran:String = "ahsn45ss74d1a37adgt4t4h1fe"
str_Ran.replacingOccurrences(of: "0", with: "Y")

And so on

Upvotes: 0

Related Questions