Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zhaodice opened this issue Dec 30, 2021 · 0 comments
Open

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

zhaodice opened this issue Dec 30, 2021 · 0 comments

Comments

@zhaodice
Copy link

zhaodice commented Dec 30, 2021

[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();
    }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant