2015-10-12 23 views
1

考慮以下字符串:Java的String修復收縮

"...Cant you, because I cant, I just CANT." 

一個如何去增加在cant所有實例的',同時仍保留資本?

"...Can't you, because I can't, I just CAN'T." 

這是我到目前爲止。它的工作原理,但似乎不必要 複雜:

public static String fix(String line) { 
    if (line == null || line.isEmpty()) { 
     return line; 
    } 

    StringBuilder builder = new StringBuilder(); 
    String[] split = line.split(" "); 

    for (String word : split) { 
     if (word.replaceAll("\\p{P}", "").equalsIgnoreCase("cant")) { // remove punctuation 
      while (word.matches("^\\p{P}.*$")) { // starts with punctuation 
       builder.append(word.charAt(0)); 
       word = word.substring(1); 
      } 
      builder.append(word.substring(0, 3)); // can 
      builder.append("'");     // ' 
      builder.append(word.substring(3)); // t 
     } else { 
      builder.append(word); 
     } 

     builder.append(" "); 
    } 

    return builder.toString().trim(); 
} 
+0

是什麼讓你覺得這個解決方案很慢?你有沒有試過計時?我運行它似乎足夠快。 – azurefrog

+0

我只是覺得這麼簡單的任務太多了。從它的外觀來看,正則表達式是解決這個問題的最佳解決方案。編輯:在原始帖子中將「緩慢」改爲「複雜」:) –

回答

3

不區分大小寫的正則表達式替換捕捉組對整條線路應該會更快:

public static String fix(String line) { 
    if (line == null) { 
     return null; 
    } 
    return line.replaceAll("(?i)\\b(can)(t)\\b", "$1'$2"); 
} 
+1

以幾秒秒爲單位擊敗我:) +1 – sam

0

問問自己,你的算法,其步驟是真的需要。最後,你是只有尋找所有出現的字符串「斜」(在這種情況下並不重要)。那麼,你爲什麼要分裂線。你爲什麼要匹配東西?