How do I take the leading consonants an move them to the end of the string?

303 Views Asked by At

The Code I am doing is, If the word starts with a consonant,it moves all leading consonats to the end of the word and adds "ay". For example "bring" to "ingbray".

1

There are 1 best solutions below

0
Bohemian On

You could use a regular expression to match leading consonants:

String pigLatin = str.replaceAll("(?i)(^[^aeiou]+)(.*)", "$2$1ay");

Breaking this down:

  • (?i) = ignore case
  • [^aeiou] = any non-vowel
  • [^aeiou]+ = 1 or more non-vowels (”greedy” match - ie as many as possible)
  • (^[^aeiou]+) = 1 or more non-vowels anchored to start, captured as group 1
  • (.*) any other characters, captured as group 2

And the replacement:

  • $2 group 2
  • $1 group 1
  • ay literal "ay"