0

I am developing translate function in Scala. It consists to insert the "av" character, just before a vowel-like 'a' , 'e' , 'i', 'o' or 'u'. Note that text string has length restrictions. It should not has a length of more than 225 characters and if it's empty, it should return an empty string: In another world: if

text = "abdcrfehilmoyr"

the result should be : "avabdcrfehavilmavoyr"

So, I developed this function :

def translate(text: String): String = {
  var voyelle = Array('a', 'e', 'i', 'o', 'u')
  for (w <- (0,text.length())){
    if ((text.contains(voyelle[w]) == true)) {
      text.patch(w, "av", 0)
    }
  }
}

Is there a way, to use instead functional programming like map, flat map functions to simplify the code ?

6
  • This code doesn't compile as-is - the for(w <- (0,text.length())) doesn't work like this. Commented Jan 20, 2022 at 13:44
  • 1
    Yes, you can use flatMap that is all you asked, hope you can find the answer. Commented Jan 20, 2022 at 13:45
  • What do you want to optimize / simplify for? As it stands the question is rather option-based and unlikely to generate a definitive answer. Commented Jan 20, 2022 at 13:45
  • @k0pernikus, I am beginner in scala, thank you if you can give me complete answer Commented Jan 20, 2022 at 13:47
  • 3
    @k0pernikus Asking specific "how-to" questions is not on-topic for CodeReview. Commented Jan 20, 2022 at 13:55

3 Answers 3

6

String is effectively a collection of char's so you can treat it like one. For example:

val result = text
  .map(c => if (voyelle.contains(c)) "av" + c else c.toString)
  .mkString
Sign up to request clarification or add additional context in comments.

2 Comments

Hello @Guru Stron, thank you for the response, but, your code adds "av" after the vowel, I am looking to add "av" before the vowel and not after it.
@Imed there was small typo. Try it out.
4

How about

   text.replaceAll("([aeiou])", "av$1")

Comments

2

You can just use flatMap

def translate(text: String): String = {
  val vowels = Set('a', 'e', 'i', 'o', 'u')
  text.trim.toLowerCase.flatMap { c =>
    if (vowels.contains(c)) s"av${c}"
    else c.toString
  }
}

code running here.

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.