Breaking News
Home / Java / Java Snippets / How to convert a String as Quoted String in Java?

How to convert a String as Quoted String in Java?

Snippet

  1.  /**
  2.    * Encloses the incoming string inside double quotes, if it isn’t already quoted.
  3.    * @param string: the input string
  4.    * @return a quoted string, of the form "input".  If the input string is null, it returns null
  5.    * as well.
  6.    */
  7.   static String convertToQuotedString(String string) {
  8.     if (string == null){
  9.       return null;
  10.     }
  11.     if (string.equalsIgnoreCase("")) {
  12.       return"";
  13.     }
  14.     int lastPos = string.length() 1;
  15.    
  16.     // if already has a quote
  17.     if (lastPos < 0 || (string.charAt(0) == ‘"’
  18.        && string.charAt(lastPos) == ‘"’)) {
  19.       return string;
  20.     }
  21.    
  22.    // append
  23.     return" + string + ";
  24.   }

<!>

[pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Advertisment ad adsense adlogger