輸入字符串,處理星號 *:中間的刪除,首尾的保留,無星號直接輸出。看似簡單,實則暗藏正則特殊字符與邊界條件陷阱。
// 錯誤:* 是正則元字符,需轉義
String[] parts = line.split("*"); // PatternSyntaxException
// 正確:雙重轉義
String[] parts = line.split("\\*");
且 split() 返回數組,直接打印輸出的是地址值而非內容,需遍歷拼接。
堅持失敗方案超 40 分鐘,未嘗試替代算法(如 StringBuilder 遍歷刪除),錯失簡單高效解法。
if (line.contains("*")) {
boolean start = line.startsWith("*");
boolean end = line.endsWith("*");
String mid = line.substring(start ? 1 : 0, end ? line.length()-1 : line.length());
String[] parts = mid.split("\\*");
StringBuilder sb = new StringBuilder();
for (String p : parts) sb.append(p);
System.out.print((start?"*":"") + sb + (end?"*":""));
}
StringBuffer sb = new StringBuffer(line);
for (int i = 1; i < sb.length()-1; i++) {
if (sb.charAt(i) == '*') {
sb.deleteCharAt(i);
i--; // 關鍵:刪除後索引回退
}
}
System.out.println(sb);
| 分隔符 | 正確寫法 | 說明 |
|---|---|---|
| . | split("\\.") | 正則元字符需雙轉義 |
| | | split("\\|") | 管道符同理 |
| * | split("\\*") | 星號同理 |
| + | split("\\+") | 加號同理 |
| \ | split("\\\\") | 四個斜桿:Java轉義+正則轉義 |
| 多字符 | split(" |-|#") | 用 | 連接多個分隔符 |
這次失利雖痛,卻是成長最寶貴的疫苗——君需更謹慎,此次失誤不可再;君當更努力,夯基迎難不可阻!