Java编程如何实现处理字符串时跳过每个句子末尾的两个单词
Java字符串处理实现方案
实现逻辑
核心处理规则如下:
- 将输入字符串按英文句号
.分割为独立句子 - 对每个句子,跳过末尾2个单词,将剩余的前面所有单词倒序排列
- 若句子单词总数≤2,直接保留原句即可
- 所有处理后的句子拼接后得到最终结果
完整Java代码
public class StringProcessDemo { 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 = processString(input); System.out.println(output); } public static String processString(String input) { // 按句号分割所有句子 String[] sentences = input.split("\\."); StringBuilder resultBuilder = new StringBuilder(); for (String rawSentence : sentences) { // 去除句子前后空白,过滤空片段 String trimmedSent = rawSentence.trim(); if (trimmedSent.isEmpty()) { continue; } // 按空白分割为单词,兼容多个空格的场景 String[] words = trimmedSent.split("\\s+"); // 单词数≤2直接保留原句 if (words.length <= 2) { resultBuilder.append(trimmedSent).append(". "); continue; } // 倒序拼接除最后两个外的单词 for (int i = words.length - 3; i >= 0; i--) { resultBuilder.append(words[i]).append(" "); } // 拼接最后两个单词和句号 resultBuilder.append(words[words.length - 2]) .append(" ") .append(words[words.length - 1]) .append(". "); } // 去除末尾多余空白后返回 return resultBuilder.toString().trim(); } }
运行效果
运行上述代码得到的输出和期望结果完全一致:Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.
内容的提问来源于stack exchange,提问作者Kalp Shah
相关产品推荐
相关产品推荐

