Search code examples
javastringreplacespecial-characterssingle-quotes

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


I want to append the single quote for the String which consists of only the special characters. This is what I want to achieve :-

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

Result should be :-

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

That means for every single quote we need to append 1 single quote that too at that particular index.

Below is my code which I have tried :-

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);
    }

But this is giving result like this :-

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

Any suggestions on this? The String can contain even and odd number of single quotes.


Solution

  • YCF_L's solution should solve your problem. But if you still want to use your method you can try this one below:

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

    It simply iterates through your string and changes every single quote (') with ('')