SWIFT checking if a string begins with something but the second character can be anything

Viewed 757

I'm new to using swift so I'm playing around with it and I'm trying to figure out how to check if a given string begins with the word "hello" though the second letter can be anything it doesn't have to be an E so I could type h0llo and it would still return true is what I'm looking to achieve.

This is the code I have so far however, it is jumbled all over the place from testing, so any help would be necessary at this stage for me. I am only adding the code so that you could understand more what it is im trying to achieve

func check(_ givenString: String) -> Bool {
    var newString = givenString

    if newString.count > 2 {
        newString.remove(at: String.Index(encodedOffset: 2))
        if newString.hasPrefix("hello") {
            return true 
        } else {
            return false
        }
    }
}
print(check("h0llo"))
1 Answers

A reasonable solution is to check with Regular Expression

func check(_ givenString: String) -> Bool {
    return givenString.range(of: "^h.llo", options: .regularExpression) != nil
}

The caret ^ checks for beginning of the string and the dot . represents any character.

Related