gpt4 book ai didi

Java 字符串修复收缩

转载 作者:行者123 更新时间:2023-11-29 04:57:54 25 4
gpt4 key购买 nike

给定以下字符串:

"...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();
}

最佳答案

在整行上用捕获组替换不区分大小写的正则表达式应该更快:

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

关于Java 字符串修复收缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com