Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string with another

Tags:

string

swift

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".

like image 399
Awais Mobeen Avatar asked Dec 21 '25 04:12

Awais Mobeen


2 Answers

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)
like image 185
vadian Avatar answered Dec 24 '25 00:12

vadian


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)
}
like image 22
Angel F Syrus Avatar answered Dec 24 '25 00:12

Angel F Syrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!