Java String Quote quoteArgument(String arg)

Here you can find the source of quoteArgument(String arg)

Description

Quotes specified string using '\"' if needed to.

License

Open Source License

Declaration

public static String quoteArgument(String arg) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from ww w  .  j av  a2 s.c  o  m
     * Quotes specified string using <tt>'\"'</tt> if needed to. Returns
     * quoted string.
     * <p>Note that whitespace characters such as '\n' and '\t' are not
     * escaped as "\n" and "\t". Instead, the whole string is quoted. This is
     * sufficient to allow it to contain any whitespace character.
     * 
     * @see #joinArguments
     */
    public static String quoteArgument(String arg) {
        int length = arg.length();

        boolean needQuotes;
        if (length == 0) {
            needQuotes = true;
        } else {
            switch (arg.charAt(0)) {
            case '\"':
            case '\'':
                needQuotes = true;
                break;
            default: {
                needQuotes = false;
                for (int i = 0; i < length; ++i) {
                    if (Character.isWhitespace(arg.charAt(i))) {
                        needQuotes = true;
                        break;
                    }
                }
            }
            }
        }
        if (!needQuotes)
            return arg;

        StringBuilder quoted = new StringBuilder();
        quoted.append('\"');
        for (int i = 0; i < length; ++i) {
            char c = arg.charAt(i);

            if (c == '\"')
                quoted.append("\\\"");
            else
                quoted.append(c);
        }
        quoted.append('\"');

        return quoted.toString();
    }
}

Related

  1. quoteAndEscapeValue(String serviceQName)
  2. quoteArg(final String arg)
  3. quoteArg(String arg)
  4. quoteArgForCommand(String input)
  5. quoteArgument(final String argument)
  6. quoteAtom(String term)
  7. quoteAtom(String term)
  8. quoteAttrValue(String s)
  9. quoteCanonical(String s)