中文的句子我还没试过,一家外企的面试题,题目大约就是把一句英文句子反转。当时我写的很乱,回家后整理到自己的印象笔记上了。有一段时间了,感觉这个写的也不是很好。以后有时间再整理下。
public class SentenceReverse {
public static void main(String[] args) {
SentenceReverse sReverse = new SentenceReverse();
Scanner input = new Scanner(System.in);
System.out.print("Pls enter the sentence you would like to reverse:");
String sentence = input.nextLine();
sReverse.reverseSentence(sentence);
}
public void reverseSentence(String sentence) {
//英文句子,将传入的字符串参数按照空格拆分成字符串数组
String[] words = sentence.split(" ");
//JavaScript的数组自带reverse方法,Java的String数组无此方法;
//将字符串数组存入数组集合中,集合中有reverse方法
List<String> wordsList = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
wordsList.add(words[i]);
}
//省略遍历,直接打印输出数组(反转前的顺序:)
System.out.println("句子拆分后:");
System.out.println(Arrays.toString(words));
//反转单词后遍历输出
Collections.reverse(wordsList);
System.out.println("反转后:");
for (String word : wordsList) {
System.out.print(word + " ");
}
}
}
输出:
Pls enter the sentence you would like to reverse:Even though I try I can't let go
句子拆分后:
[Even, though, I, try, I, can't, let, go]
反转后:
go let can't I try I though Even