patternjavaMinor
Reverse words in Java
Viewed 0 times
javawordsreverse
Problem
Short and Spicy question is that If input is
How can I improve my code? And Is there any other way to do it with less time and space complexity?
how are you and output should beyou are how.public class ReverseWord {
public static void main(String[] args) throws IOException{
String input;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the input string");
input = br.readLine();
System.out.println("Enterd String:"+input);
System.out.println("Reversed:"+reverse(input));
}
public static String reverse(String input){
String delimiter = " ";
String[] splits = input.split(delimiter);
String reverse = new String("");
for(int i=splits.length-1; i>=0; i--){
//System.out.println(splits[i]);
reverse += splits[i];
reverse = reverse.concat(delimiter);
}
System.out.println(reverse);
return reverse;
}
}How can I improve my code? And Is there any other way to do it with less time and space complexity?
Solution
The odd behaviour is that the result gets printed twice: once in
The output will also include an extra space at the end. It may be invisible, but I would consider it technically incorrect.
Your code, with those issues fixed, and a few tweaks:
However, repeated string concatenation is inefficient: every
reverse(), and again in main(). reverse() should be fixed so that it returns the result without printing it.The output will also include an extra space at the end. It may be invisible, but I would consider it technically incorrect.
Your code, with those issues fixed, and a few tweaks:
public static String reverse(String input) {
String delimiter = " ";
String[] splits = input.split(delimiter);
String reverse = ""; // Same as new String("")
for (int i = splits.length - 1; i > 0; i--) { // Be more generous with spaces
reverse += splits[i] + delimiter; // Get rid of .concat()
}
if (splits.length > 0) {
reverse += splits[0];
}
return reverse;
}However, repeated string concatenation is inefficient: every
+= involves allocating a new buffer and copying everything. You should really be using a StringBuilder, like this. (Other suggested solutions in that question are also quite good. You should study those answers and form your own opinion.)Code Snippets
public static String reverse(String input) {
String delimiter = " ";
String[] splits = input.split(delimiter);
String reverse = ""; // Same as new String("")
for (int i = splits.length - 1; i > 0; i--) { // Be more generous with spaces
reverse += splits[i] + delimiter; // Get rid of .concat()
}
if (splits.length > 0) {
reverse += splits[0];
}
return reverse;
}Context
StackExchange Code Review Q#123516, answer score: 5
Revisions (0)
No revisions yet.