java - 在Java中反转句子
问题描述
解决方案
你可以简单地做到这一点
public class Main {
public static void main(String[] args) {
// Split on whitespace
String[] arr = "pay no attention to that man behind the curtain".split("\\s+");
// Print the array in reverse order
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
}
}
输出:
curtain
the
behind
man
that
to
attention
no
pay
或者,
public class Main {
public static void main(String[] args) {
String s1 = "pay no attention to that man behind the curtain";
for (int i = s1.length() - 1; i >= 0; i--) {
if (s1.charAt(i) == ' ') {
// Print the last word of `s1`
System.out.println(s1.substring(i + 1));
// Drop off the last word and assign the remaining string to `s1`
s1 = s1.substring(0, i);
} else if (i == 0) {
// If `s1` has just one word remaining
System.out.println(s1);
}
}
}
}
输出:
curtain
the
behind
man
that
to
attention
no
pay
推荐阅读
- laravel - 如何使用laravel检查记录是否存在于数据库中?
- python - 为什么它不识别模块?(Python 3.7)
- ios - Fabric:集成服务挂钩 GitLab 失败并出现 HTTP 308
- android - Unity 广告在我的 Android 应用中持续显示
- grpc - gRPC Java 服务器:有什么方法可以获取从客户端接收到的原始消息字节?
- ios - SOAP API 在可选括号中响应 XML。如何迎合它?
- python - 如何在python3.7中添加参数
- hyperledger - 超级账本结构是否被视为集中式区块链
- javascript - 循环遍历对象中的段落。如何?
- javascript - 无法在移动视图reactjs中触发滚动事件