輸入文章(句子以 `.` 分隔)與關鍵字,輸出包含關鍵字的句子及其前後句,關鍵字大寫高亮。邊界情況:首句無前句、尾句無後句。
public static String findContext(String text, String keyword) {
String[] sentences = text.split("\\."); // 保留分隔符需用正則看前瞻,此處簡化
String lowerText = text.toLowerCase();
String lowerKey = keyword.toLowerCase();
for (int i = 0; i < sentences.length; i++) {
if (sentences[i].toLowerCase().contains(lowerKey)) {
StringBuilder sb = new StringBuilder();
if (i > 0) sb.append(sentences[i - 1]).append(". ");
sb.append(sentences[i]).append(". ");
if (i < sentences.length - 1) sb.append(sentences[i + 1]).append(". ");
// 高亮關鍵字(簡化:僅首次出現)
return sb.toString().replaceFirst("(?i)" + keyword, keyword.toUpperCase());
}
}
return "";
}
| 問題 | 解決方案 |
|---|---|
| 分割後丟失 `.` | 拼接時手動添加 . ,或使用 split("(?<=\\.)") 保留分隔符 |
| 大小寫不敏感查找 | 統一轉小寫比對,輸出時用正則 (?i) 替換首次匹配為大寫 |
| 空指針異常 | 循環邊界檢查 i>0、i |
| 靜態方法要求 | 聲明 public static String findContext(...),主方法直接調用 |
String text = "Abc. Def. Ghk. Gml. Zkb.";
System.out.println(findContext(text, "e")); // 輸出: Abc. DEf. Ghk.
System.out.println(findContext(text, "z")); // 輸出: Gml. Zkb.
靜態方法無實例狀態,適合工具類封裝。字符串分割、大小寫處理、邊界檢查、正則替換是核心技能點。注意 split("\\.") 會丟失分隔符,實際項目建議使用 Pattern.split 配合看前瞻/後顧保留標點。