Reputation: 67
I tried to make a method to reverse an array of strings and return a string array with all the words in reverse order. However my code does not work.
public static String[] reverse(String input) {
String[] reversed = new String[input.length()];
for (int i = 0; i < input.length(); i++){
StringBuilder sb = new StringBuilder(input[i]);
reversed[i] = sb.reverse().toString();
}
return reversed;
}
The input in StringBuilder line shows error "array type expected; found: 'java.lang.String'. I cannot figure it out.
The expected results show be like:
String[] reversed = StringReverser.reverse("grey fox jumps over dog");
assertArrayEquals(new String[] {
"dog","over", "jumps", "fox", "grey"}, reversed);
Upvotes: -5
Views: 2057
Reputation: 1
Use this youtube video for complete logic to write the code
String s = "Reverse Each Word"; // EXPECTED OUTPUT:- "esreveR hcaE droW"
Upvotes: 0
Reputation: 18245
There are two problems with your code:
input[i]
to new StringBuilder(...)
whereas input
is not an array.public static String[] reverse(String input) {
String[] words = input.split("\\s+");
for (int i = 0, j = words.length - 1; i < j; i++, j--)
swap(words, i, j);
return words;
}
private static void swap(String[] arr, int i, int j) {
String tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Demo:
String[] res = reverse("grey fox jumps over dog");
System.out.println(Arrays.toString(res)); // [dog, over, jumps, fox, grey]
Upvotes: 0
Reputation: 79035
There are two problems with your code:
input[i]
to new StringBuilder(...)
whereas input
is not an array.Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(reverse("grey fox jumps over dog")));
}
public static String[] reverse(String input) {
String[] words = input.split("\\s+");
String[] reversed = new String[words.length];
for (int i = 0; i < words.length; i++) {
reversed[words.length - i - 1] = words[i];
}
return reversed;
}
}
Output:
[dog, over, jumps, fox, grey]
Upvotes: 2