在我的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.
有人幫助嗎?
uj5u.com熱心網友回復:
嘗試這個。
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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/368301.html
上一篇:計算二維字串中的所有元音
