Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

arrays - 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);
question from:https://stackoverflow.com/questions/65876762/reverse-each-word-in-a-string-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...