java倒序输出英文句子_英文句子反转 -- 面试题(Java)

中文的句子我还没试过,一家外企的面试题,题目大约就是把一句英文句子反转。当时我写的很乱,回家后整理到自己的印象笔记上了。有一段时间了,感觉这个写的也不是很好。以后有时间再整理下。

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 wordsList = new ArrayList();

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值