I want to replace "a" with "an" in a sentence; e.g. "He has a egg in his bag", so that there'd be "an" before "egg".
I tried this:
let newString = "He has a egg in his bag".replacingOccurrences(of: "a", with: "an")
print(newString)
– but I get "he hans an egg in his bang" instead of getting "he has an egg in his bag".
I know the rule is much more complex than adding an n before a vowel (even that) but this is a solution with Regular Expression.
It adds an n to a single a before a word starting with a vowel. The $1 represents the captured vowel
let string = "He has a egg in a bag"
let newString = string.replacingOccurrences(of: "\\ba\\s([aeiou])", with: "an $1", options: .regularExpression)
Add some extra space with the letter "a".
Change your code as,
if self.addedText.count > 0{
let newString = self.addedText.replacingOccurrences(of: " a ", with: " an ")
print(newString)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With