Reverse Vowels
June 4, 2019
Now that school is finished for the year, I’m catching up on the homework questions that people have sent me over the last several months. This one is fun:
Given a string, write it with the vowels reversed, maintaining the original capitalization of the vowels. For instance, “HELLO world” becomes “HOLLO werld” and “Programming PRAXIS” becomes “Prigramming PRAXOS” (I kinda like that one).
Your task is to write a program that returns an input string with vowels in reverse order, respecting the original capitalization. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
I decided to use a functional style instead of the perhaps more
obvious in-place replacement of characters in an array. My program
(written without peeking at the solution) ended up being almost the
same as the first one by programmingpraxis, except for the slight
optimization of avoiding a couple of reverses. Here it is for
completeness sake.
Mumps version
A Haskell version.
Klong version
Rust version:
Playground link https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=60f83463ee1eca11e929173b886da670
Rust version:
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=60f83463ee1eca11e929173b886da670
Rust version without custom iterator
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=54bac1b236904a178f7eb8ba8e5714e8
Here’s a solution in Python.
Output:
LOCOMOTIVE BASIC
10 REM Reverse Vowels by SRS 05.03.2020
20 MODE 2
30 PRINT “Please enter a string; this program will then reverse the vowels in that string,”:PRINT “maintaining the original capitalisation of the vowels.”
40 PRINT
50 INPUT”Your String:”,s$
60 FOR i=LEN(s$) TO 1 STEP -1:c$=MID$(s$,i,1):IF INSTR(“aeiouAEIOU”,c$) THEN rv$=rv$+c$
70 NEXT
80 FOR i=1 TO LEN(s$):c$=MID$(s$,i,1):IF INSTR(“aeiou”,c$) THEN rs$=rs$+LOWER$(LEFT$(rv$,1)):rv$=RIGHT$(rv$,LEN(rv$)-1):GOTO 110
90 IF INSTR(“AEIOU”,c$) THEN rs$=rs$+UPPER$((LEFT$(rv$,1))):rv$=RIGHT$(rv$,LEN(rv$)-1):GOTO 110
100 rs$=rs$+c$
110 NEXT
120 PRINT “My Output: “;rs$