跳过 java 中句子的最后 2 个单词
Skip last 2 words in a sentence in java
在我的java程序中,
如何跳过句子中的最后两个词?
我的输入字符串是:Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.
预期输出为:Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
有人帮忙吗?
试试这个。
static String reverseExceptLast2Words(String input) {
StringBuilder output = new StringBuilder();
for (String senence : input.split("\.\s*")) {
List<String> words = Arrays.asList(senence.split("\s+"));
Collections.reverse(words.subList(0, Math.max(0, words.size() - 2)));
output.append(String.join(" ", words)).append(". ");
}
return output.toString();
}
public static void main(String[] args) {
String input = "Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.";
String output = reverseExceptLast2Words(input);
System.out.println(output);
}
输出:
Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
在我的java程序中,
如何跳过句子中的最后两个词?
我的输入字符串是:Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.
预期输出为:Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
有人帮忙吗?
试试这个。
static String reverseExceptLast2Words(String input) {
StringBuilder output = new StringBuilder();
for (String senence : input.split("\.\s*")) {
List<String> words = Arrays.asList(senence.split("\s+"));
Collections.reverse(words.subList(0, Math.max(0, words.size() - 2)));
output.append(String.join(" ", words)).append(". ");
}
return output.toString();
}
public static void main(String[] args) {
String input = "Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.";
String output = reverseExceptLast2Words(input);
System.out.println(output);
}
输出:
Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.