Search code examples
swiftreplacenumbersletters

Find out if a string has a number in a specific position


Is it possible to have a string for example:

var myText = "AB12CDE"

and then check to see if 3rd and 4th letters are numbers and if not change it to a number.

So if the above text ended up being:

"ABIZCDE" 

I would be able to change IZ to 12 but not replacing all instances of I and Z but only in the 3rd and 4th charecther.


Solution

  • Here is it:

    let str = "ABCIZCDEZ"
    var newString = ""
    var index = 0
    str.forEach { (char) in            
        var charToAppend = char
        if index == 3 || index == 4 {
            if char == "Z" {
                charToAppend = "2"
            }
            if char == "I" {
                charToAppend = "1"
            }
        }
        newString.append(charToAppend)
        index += 1
    }
    
    print(newString) // ABC12CDEZ
    

    For insertion for example you could make an extension:

    Add this somewhere before your class:

    public extension String {
        public func insert(string: String, index: Int) -> String {
            return String(self.prefix(index)) + string + String(self.suffix(self.count - index))
        }
    }
    

    Then:

    let str2 = "ABC2CDEZ"
    var newString = str2.insert(string: "I", index: 3)
    print(newString) // ABCI2CDEZ