Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

32
LINES

< > BotCompany Repo | #1005595 // quote - Java-compatible string quoting with "". now also escapes \t

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2489L/16K).

static S quote(O o) {
  if (o == null) return "null";
  ret quote(str(o));
}

static S quote(S s) {
  if (s == null) return "null";
  StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
  quote_impl(s, out);
  ret out.toString();
}
  
static void quote_impl(S s, StringBuilder out) {
  out.append('"');
  int l = s.length();
  for (int i = 0; i < l; i++) {
    char c = s.charAt(i);
    if (c == '\\' || c == '"')
      out.append('\\').append(c);
    else if (c == '\r')
      out.append("\\r");
    else if (c == '\n')
      out.append("\\n");
    else if (c == '\t')
      out.append("\\t");
    else if (c == '\0')
      out.append("\\0");
    else
      out.append(c);
  }
  out.append('"');
}

Author comment

Began life as a copy of #1001239

download  show line numbers  debug dex  old transpilations   

Travelled to 16 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, podlckwnjdmb, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, whxojlpjdney, xrpafgyirdlv

No comments. add comment

Snippet ID: #1005595
Snippet name: quote - Java-compatible string quoting with "". now also escapes \t
Eternal ID of this version: #1005595/6
Text MD5: e251fab9c3975a14d85fa27c36dd7152
Transpilation MD5: 62fa5a2ca6587d0f03346339b3fa5f94
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-08-09 15:44:29
Source code size: 736 bytes / 32 lines
Pitched / IR pitched: No / No
Views / Downloads: 840 / 1427
Version history: 5 change(s)
Referenced in: #1005594 - Benchmark quote()
#1005966 - quoteToPrintWriter
#1006654 - Standard functions list 2 (LIVE, continuation of #761)
#1009089 - singleQuote - enclose string in single quotes ('); doesn't escape "; not a Java construct
#1012823 - quoteBorderless - quote() without surrounding double quotes
#1029312 - quoteShorten