考慮以下字符串: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();
}
是什麼讓你覺得這個解決方案很慢?你有沒有試過計時?我運行它似乎足夠快。 – azurefrog
我只是覺得這麼簡單的任務太多了。從它的外觀來看,正則表達式是解決這個問題的最佳解決方案。編輯:在原始帖子中將「緩慢」改爲「複雜」:) –