gpt4 book ai didi

java - 替换字符串中重复字符的最佳方法

转载 作者:行者123 更新时间:2023-12-01 11:17:41 28 4
gpt4 key购买 nike

我得到了字符串“('allan', 'bob's', 'charles', 'dom')”。现在我需要这个字符串,但格式为 "('allan', 'bob''s', 'charles', 'dom')"

请注意,我已将 bob's 替换为 bob''s,仅此而已。我最初的解决方案是这样的

String str = "('allan', 'bob's', 'charles', 'dom')";
String[] elements = str.substring(1, str.length()-1).split(", ");
String res = "(";
for (int j = 0; j < elements.length; j++) {
res += "'"+ elements[j].substring(1, elements[j].length()-1).replace("'", "''") + "'" + ((j == elements.length - 1) ? ")" : ",' ");
}

其中 res 是最终的解决方案。不过我想知道是否有一个更短、更优雅的解决方案?

最佳答案

replaceAll 将使用 "'s" 作为正则表达式。

  public static void main(String[] args) {
String str = "('allan', 'bob's', 'charles', 'dom')";
str = str.replaceAll("'s", "''s");
System.out.println(str);
}

输出:

('allan', 'bob''s', 'charles', 'dom')

关于java - 替换字符串中重复字符的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612426/

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