A friend of mine was asked to write the following program in an interview. He asked me how to do it?
Write a program to reverse the order of the words in a given statement (string). e.g. if input string is “India is a great country”, Output should be “country great a is India”.
This is one of the pet string questions in the interviews. I tried the implementation of a neat way of solving the problem. Here it is. Its not noval way. Algorithm uses iteration. Can you write a recursive one ?
Program is simple and self explanatory about the algorithm.
Update: I just tried writing it in shell – Bash.
#!/bin/bash
INSTR=$1
FINALSTR=”"
for i in $INSTR; do
TMP=`echo $i | rev`
FINALSTR=”$FINALSTR $TMP”
doneecho IN : $INSTR
echo OUT: $FINALSTR
Filed under: Programming, technical
Ah, I think what you are looking for is this.
#!/bin/bash
out=”"
for w in $1; do
out=”$w $out”
done
echo $out