Say I have a string that contains three underscores
var myString = "___"
Given a number, the string should look like this
myString = "1__"
If the user types a new number, say 2, the string will change
myString = "12_"
Given a number
, I tried coding this situation:
for i in myString.characters {
if (i == "_") {
newString = myString.stringByReplacingOccurrencesOfString("_", withString: number, options: NSStringCompareOptions.LiteralSearch, range: nil)
break
}
}
The problem is that stringByReplacingOccurrencesOfString
replaces the characters all at once. What string method do you think I should use instead?
You can take the user input string and pad it with '_':
var userInput = "1" // This is the string from the text field input by the user
var finalText = userInput.stringByPaddingToLength(3, withString: "_", startingAtIndex: 0)
I'd personally vote for @giorashc:s native padding solution (*), but to additionally add to the variety of answers this question (as this Q&A already contains a few variations), you could also make use of the suffixFrom(...)
method for the CharacterView
of your template string (___
) to achieve the padding behaviour. E.g.:
/* Example (if length of string >= template: just return string) */
let padToTemplate: (str: String, withTemplate: String) -> String = {
return $0.characters.count < $1.characters.count
? $0 + String($1.characters.suffixFrom($0.characters.endIndex))
: $0
}
/* Example usage */
let myString = padToTemplate(str: "1", withTemplate: "___")
print(myString) // 1__
(*) Thanks @KennethBruno for pointing out that .stringByPaddingToLength(..)
is from NSString
and not native Swift!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With