Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String methods in Swift to replace the first character in a string

Tags:

string

ios

swift

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?

like image 781
Cesare Avatar asked Dec 15 '22 07:12

Cesare


2 Answers

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)
like image 148
giorashc Avatar answered Feb 09 '23 00:02

giorashc


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!

like image 26
dfrib Avatar answered Feb 08 '23 23:02

dfrib