Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing a char in a string based on a condition

I came across this question in CodeWars recently & tried to solve it using Swift 5 (which I’m new to):

Given a string of digits, you should replace any digit below 5 with ‘0’ and any digit 5 and above with ‘1’. Return the resulting string.
Note: input will never be an empty string

I come from a Python background where we could using indexing with if statements to solve this particular problem like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def bin(x):
    newstr = ""
    for num in x:
        if int(num) < 5:
            newstr += "0"
        else:
            newstr += "1"
    return newstr

But when I tried to use indexing in Swift( like the Python style), I failed…which, after a while of researching made me come across this method: String.replacingOccurrences(of: , with: )

So if my Swift code for the above ques is like this:

func fakeBin(digits: String) -> String {
  
  for i in digits{
    
    if (Int(i)<5){
      some code to replace the char with '0'
    }
    else{some code to replace the char with '1'}
  
    return digits
  }

How do I use the above method String.replacingOccurrences(of: , with: ) in my code and achieve the desired output? If this is not possible, how else can we do it?

Note: I have already looked up for solutions on the website & found one:How do I check each individual digit within a string? But wasn’t of any use to me as the questioner wanted the help in Java

>Solution :

A Swift String is a collection of Characters. You can map each character to "0" or "1", and join the result to a new string:

func fakeBin(digits: String) -> String {
    return String(digits.map { $0 < "5" ? "0" : "1" })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading