/**
* ReverseWordsOfAString simply reverses individual words of a string.
* Keep the order of words intact
*
*/
import java.io.*;
class ReverseWordsOfAString
{
public static final int UNKNOW=0;
public static final int INTERACTIVE=1;
public static final int TEST=10;
public static final int BATCH=20;
public static void main(String[] args)
{
switch ( ReverseWordsOfAString.parseCommandLine( args ) )
{
case ReverseWordsOfAString.INTERACTIVE:
ReverseWordsOfAString.executeInteractive( args );
break;
case ReverseWordsOfAString.TEST:
ReverseWordsOfAString.executeTest( args );
break;
default:
System.out.println("Other functions not yet implemented");
}
}
public static int parseCommandLine(String[] args)
{
if (args[0].equals("--interactive"))
return ReverseWordsOfAString.INTERACTIVE;
if (args[0].trim().equals("--test"))
return ReverseWordsOfAString.TEST;
if (args[0].equals("--batch"))
return ReverseWordsOfAString.BATCH;
return ReverseWordsOfAString.UNKNOW;
}
public static void executeInteractive( String[] args )
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (str != null)
{
System.out.print("> interactive [Hit CTRL-D to exit] ");
str = in.readLine();
System.out.println(processReverseWordsOfAString(str));
}
} catch (IOException e) {}
}
public static void executeTest( String[] args )
{
long start = System.currentTimeMillis();
assert processReverseWordsOfAString("hello francois").equals("olleh siocnarf");
assert processReverseWordsOfAString("hello francois richard how are you doing").equals("olleh siocnarf drahcir woh era uoy gniod");
long end = System.currentTimeMillis();
System.out.println("Elapsed time: " + (end - start) );
}
public static String processReverseWordsOfAString (String arg)
{
if (arg == null)
{
System.out.println("");
System.exit(1);
}
StringBuffer result = new StringBuffer();
StringBuffer word = new StringBuffer();
for (int i=0; i {
if (arg.charAt(i) != ' ' )
word.append(arg.charAt(i));
if (arg.charAt(i) == ' ' )
{
for (int j=word.length()-1; j>=0; j--)
result.append(word.charAt(j));
result.append(" ");
word = new StringBuffer();
}
if (i == arg.length()-1)
{
for (int j=word.length()-1; j>=0; j--)
result.append(word.charAt(j));
}
}
return result.toString();
}
}
Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/Idisu6G40lk/11763