簡體   English   中英

將字符串轉換為字符串數組后無法反向

[英]Unable to reverse a String after converting it to String Array

我正在嘗試使用split方法將String轉換為String Array 當我嘗試使用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();

        }

    }

編譯器消息很清楚: reverse不是String的方法。

嘗試:

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

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);
            }

        }

沒有為String類型定義reverse方法。 您可以在List上使用Collections#reverse來反轉其元素:

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

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

這是因為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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM