给出以下字符串:
"...Cant you, because I cant, I just CANT."
如何在'
的所有实例中添加cant
,同时仍保留大写字母?
"...Can't you, because I can't, I just CAN'T."
这是我到目前为止所拥有的。它有效,但似乎不必要 slow 复杂:
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 :(得分:3)
在整行上使用捕获组替换不区分大小写的正则表达式应该更快:
public static String fix(String line) {
if (line == null) {
return null;
}
return line.replaceAll("(?i)\\b(can)(t)\\b", "$1'$2");
}
答案 1 :(得分:0)
问问自己,算法中确实需要哪些步骤。最后,您仅寻找所有出现的字符串" cant" (在这种情况下并不重要)。所以,你为什么要拆分这条线。你为什么匹配的东西?