I am writing 3 methods which can print an input string vertically (one line). But I am unaware of the best method since benchmarking with System.nanoTime() considerably changes with large variations, I mean if I calculate the time difference between start and end of the process. Please suggest which is best or better, opine what you think according to your knowledge.
Code snippet #1
/**
* Prints all the characters in the argument string vertically using loop
* @param str
*/
public static void toVertStringLoop(String str){
if(str != null && !"".equals(str)){
int strLen = str.length();
for (int i=0; i<strLen; i++){
System.out.println(str.charAt(i));
}
}
}
Code snippet #2
/**
* Prints all the characters in the argument string vertically using recursion
* @param str
*/
public static void toVertStringRecur(String str){
if (str != null && !"".equals(str)){
System.out.println(str.charAt(0)); //print the first character
toVertStringRecur(str.substring(1, str.length())); //recursively call removing the first character
}
}
Code snippet #3
/**
* Prints all the characters in the argument string vertically using for-each loop
* @param str
*/
public static void toVerticalStringIterator(String str){
//for-each loop needs array or Iterator instance
for(char ch : str.toCharArray()){
System.out.println(ch);
}
}