avidCoder
avidCoder

Reputation: 490

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.

Upvotes: 1

Views: 3192

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

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.

Upvotes: 2

ozata
ozata

Reputation: 562

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

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

All you need is just replace :

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

Outputs

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

Upvotes: 4

Related Questions