简体   繁体   中英

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.

All you need is just replace :

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

Outputs

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

You will just need to use String .replaceAll() method :

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

This is a live working Demo .

Note:

Using a for loop for this is an overkill when .replace() or .replaceAll() are enough, there is no need to reinvent the wheel.

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 ('')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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