[英]Skip last 2 words in a sentence in java
In my java program,在我的 java 程序中,
How to skip last two words in sentence?如何跳过句子中的最后两个单词?
My input string is: Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.
我的输入字符串是: Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.
Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.
Expected output is: Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
预期的 output 是: Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
Anyone Help?有人帮忙吗?
Try this.尝试这个。
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);
}
output: output:
Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.