user572490
user572490

Reputation: 67

Reverse each word in a string in Java

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

Answers (3)

user29517147
user29517147

Reputation: 1

Use this youtube video for complete logic to write the code

String s = "Reverse Each Word"; // EXPECTED OUTPUT:- "esreveR hcaE droW"

https://youtu.be/Jb9y7mCbUpM

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

There are two problems with your code:

  1. You have passed input[i] to new StringBuilder(...) whereas input is not an array.
  2. You have not reversed the string word-wise at all. There can be many ways to do it. The easiest way is to split the string on whitespace and the store them in an array in the reversed order.
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

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79035

There are two problems with your code:

  1. You have passed input[i] to new StringBuilder(...) whereas input is not an array.
  2. You have not reversed the string word-wise at all. There can be many ways to do it. The easiest way is to split the string on whitespace and the store them in an array in the reversed order.

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

Related Questions