[英]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.