0

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.

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

3 Comments

Huh, faster than me with the exact same solution, even the function name is the same. The only difference is that I have used options: .caseInsensitive.
@Sulthan, thanks for the hint, but .caseInsensitive doesn't seem to consider the character set.
@vadiant Interesting. Another quirk of the String API... I would probably use [aeiou] regular expression anyway :)
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.