Srinivasan
Srinivasan

Reputation:

Java String Special character replacement

I have string which contains alpahanumeric and special character. I need to replace each and every special char with some string.

For eg,

Input string = "ja*va st&ri%n@&" Expected o/p = "jaasteriskvaspacestandripercentagenatand"

thanks,

Upvotes: 1

Views: 12251

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500675

Unless you're absolutely desperate for performance, I'd use a very simple approach:

String result = input.replace("*", "asterisk")
                     .replace("%", "percentage")
                     .replace("@", "at"); // Add more to taste :)

(Note that there's a big difference between replace and replaceAll - the latter takes a regular expression. It's easy to get the wrong one and see radically different effects!)

An alternative would be something like:

public static String replaceSpecial(String input)
{
    // Output will be at least as long as input
    StringBuilder builder = new StringBuilder(input.length());

    for (int i = 0; i < input.length(); i++)
    {
        char c = input.charAt(i);
        switch (c)
        {
            case '*': builder.append("asterisk"); break;
            case '%': builder.append("percentage"); break;
            case '@': builder.append("at"); break;
            default: builder.append(c); break;
        }
    }
    return builder.toString();

Upvotes: 9

Brandon E Taylor
Brandon E Taylor

Reputation: 25349

Take a look at the following java.lang.String methods:

Upvotes: 0

Related Questions