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:
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