1

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.

2 Answers 2

1

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) }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I already try that but showing Expressions are not allowed at the top level error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.