3

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

3
  • 5
    And what if the sentence is "he has a egg in a bag"? Commented Aug 22, 2019 at 9:45
  • 2
    it will replace a with an everywhere in string. if you want to make change on specific position you can approach it by index. Commented Aug 22, 2019 at 9:50
  • it will be like "he hans ann egg in his bang" Commented Sep 5, 2019 at 12:14

3 Answers 3

3

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

3 Comments

One could use a “word boundary” \b instead of the first \s so that it works at the beginning of a sentence.
@MartinR This would cause the sentence to start with a space character so you would have to add other parentheses to capture more characters and change the replace term (like in the answer of Thanh).
The word boundary is not captured. I mean something like replacingOccurrences(of: "\\ba\\s([aeiou])", with: "an $1", ...). I cannot test it currently.
3

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)
}

1 Comment

this will not replace the "a" with "an" if the sentence will be like "a orange was in his bag" so you have to use regex to solve this kind of problem as an answer is given below. thanks
1

I capture a before a word begin with a,e,i,o,u using regex and replace.

if self.addedText.count {
  let newString = string.replacingOccurrences(of: "(\\b)a(\\s)([aeiou])", with: "$1an$2$3", options: .regularExpression)
  print(newString)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.