将String转换为String Array后无法反转String

时间:2014-11-24 19:27:09

标签: java arrays eclipse string

我正在尝试使用String方法将String Array转换为split。当我尝试使用reverse方法单独反转数组的元素时,reverse方法甚至不会显示在Eclipse代码建议中。明确使用reverse,会发出错误The method reverse() is undefined for the type String。 请帮忙!

public class Split {

    public static void main(String args[]){

        String temp;

        String names="Apple Banana Cabbage Daffodil";

        String[] words = names.split(" ");

        for (int i = 0; i < words.length; i++) {

            temp = words[i].reverse();

        }

    }

4 个答案:

答案 0 :(得分:3)

编译器消息很明确:reverse不是String的方法。

尝试:

String reverse = new StringBuilder(words[i]).reverse().toString();

答案 1 :(得分:1)

String类型没有反向方法,但您可以自己完成:

public static void main(String args[]){

            String temp;

            String names="Apple Banana Cabbage Daffodil";

            String[] words = names.split(" ");
            String[] reverseWords = new String[words.length];
            int counter = words.length - 1;
            for (int i = 0; i < words.length; i++) {
                reverseWords[counter] = new String(words[i]);
                counter--;
            }
            words = reverseWords;
            for(String i : words)
            {
                System.out.print(" " + i);
            }

        }

答案 2 :(得分:1)

没有为reverse类型定义String方法。您可以在List上使用Collections#reverse来反转其元素:

String[] words = names.split(" ");

List<String> wordList = Arrays.asList(words);
Collections.reverse(wordList);

答案 3 :(得分:1)

因为String没有方法反向,所以你可以使用 StringBuilder

像:

public static void main(String[] args) {

    String temp;

    String names = "Apple Banana Cabbage Daffodil";

    String[] words = names.split(" ");

    for (int i = 0; i < words.length; i++) {

        temp = new StringBuilder(words[i]).reverse().toString();
    }
}