繁体   English   中英

Append 使用 Java 到特殊字符串的单引号 (')

[英]Append single quote (') to a Special Character String using Java

我想 append 只包含特殊字符的字符串的单引号。 这就是我想要实现的目标:-

String sp = ''{+#)''&$;

结果应该是:-

'''' {+#)''''&$

这意味着对于每个单引号,我们也需要在该特定索引处 append 1 个单引号。

以下是我尝试过的代码:-

public static String appendSingleQuote(String randomStr) {
        if (randomStr.contains("'")) {
            long count = randomStr.chars().filter(ch -> ch == '\'').count();
            for(int i=0; i<count; i++) {
                int index = randomStr.indexOf("'");
                randomStr = addChar(randomStr, '\'', index);
            }
            System.out.println(randomStr);
        }
        return randomStr;
    }

    private static String addChar(String randomStr, char ch, int index) {
        return randomStr.substring(0, index) + ch + randomStr.substring(index);
    }

但这给出了这样的结果:-

'''''' {+#)''&$

对此有何建议? 字符串可以包含偶数和奇数个单引号。

您只需要replace

String str = "''{+#)''&$";
str = str.replace("'", "''");

输出

''''{+#)''''&$

您只需要使用String .replaceAll()方法

String sp =" ''{+#)''&$";
sp.replaceAll("\'", "''")

这是一个现场工作演示

笔记:

.replace().replaceAll()足够时,为此使用for循环是一种过度杀伤,无需重新发明轮子。

YCF_L 的解决方案应该可以解决您的问题。 但是,如果您仍然想使用您的方法,您可以尝试以下方法:

public String appendSingleQuote(String randomStr) {
    StringBuilder sb = new StringBuilder();
    for (int index = 0 ; index < randomStr.length() ; index++) {
        sb.append(randomStr.charAt(index) == '\'' ? "''" : randomStr.charAt(index));
    }
    return sb.toString();
}

它只是遍历您的字符串并用 ('') 更改每个单引号 (')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM