Stefan Claussen
Stefan Claussen

Reputation: 53

Returning a substring after a specified character

If I have a string, e.g. spider, how do you create a new string that starts at the first vowel and ends with the last character of the initial string.

For example: - spider would be ider - elephant would be elephant - campus would be ampus

Thank you for the help.

Upvotes: 0

Views: 538

Answers (2)

vadian
vadian

Reputation: 285290

Simple solution with a custom CharacterSet as String extension

extension String {

    func substringFromFirstVowel() -> String
    {
        let vowelCharacterSet = CharacterSet(charactersIn: "aeiouAEIOU")
        guard let range = self.rangeOfCharacter(from: vowelCharacterSet) else { return self }
        return self.substring(from: range.lowerBound)
    }
}


"elephant".substringFromFirstVowel() // elephant
"spider".substringFromFirstVowel() // ider
"campus".substringFromFirstVowel() // ampus 

Upvotes: 3

Luke Chase
Luke Chase

Reputation: 322

Try this little function

func firstVowel(input : String) -> String {
    var firstVowel = true
    let vowels = "aAeEiIoOuU".characters
    var result = ""

    for char in input.characters {

        if(!firstVowel) {
            result.append(char)
        }

        if(vowels.contains(char) && firstVowel) {
            firstVowel = false
            result.append(char)
        }
    }
    return result
}

print(firstVowels(input: "elephant")) //prints elephant
print(firstVowels(input: "Spider")) //prints ider

Upvotes: 0

Related Questions