Skip to content

Cannot express string "\n" with "\\n"  #77

@zhaodice

Description

@zhaodice

[test]
a="""
\\n
"""

when I read the key named "a", I got "\{ENTER}" rather than string "\n",I found the function "replaceSpecialCharacters" directly replaced "\n" with "{ENTER}",so I cannot express the pure string \n

to resolve this issue,we can replace this function , the following works for me.

package com.moandjiezana.toml;
...
  String replaceSpecialCharacters(String s) {
    for (int i = 0; i < s.length() - 1; i++) {
      char ch = s.charAt(i);
      char next = s.charAt(i + 1);

      if (ch == '\\' && next == '\\') {
        i++;
      } else if (ch == '\\' && !(next == 'b' || next == 'f' || next == 'n' || next == 't' || next == 'r' || next == '"' || next == '\\')) {
        return null;
      }
    }

    return s.replace("\\n", "\n")
      .replace("\\\"", "\"")
      .replace("\\t", "\t")
      .replace("\\r", "\r")
      .replace("\\\\", "\\")
      .replace("\\/", "/")
      .replace("\\b", "\b")
      .replace("\\f", "\f");
  }

replace it with :

  String replaceSpecialCharacters(String s) {
    char next='\0';
    StringBuilder stb = new StringBuilder();
    for (int i = 0; i < s.length() - 1; i++) {
      char ch = s.charAt(i);
      next = s.charAt(i + 1);
      if (ch == '\\') {
        switch (next){
          case '\\':{ stb.append('\\');break;}
          case 'b':{ stb.append('\b');break; }
          case 'f':{ stb.append('\f');break; }
          case 'n':{ stb.append('\n');break; }
          case 't':{ stb.append('\t');break; }
          case 'r':{ stb.append('\r');break; }
          case '"':{ stb.append('"');break; }
          default:{ return null; }
        }
        i++;
      }else{
        stb.append(ch);
      }
    }
    if(next=='\0') {
      return s;
    }else{
      stb.append(next);
      return stb.toString();
    }
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions