简体   繁体   中英

Java - Converting escaped string to chars

Edit: False! The code below works, in my instance the string is being read as "\\n", which gives me 2 characters rather than one. I am silly.

I'm trying to convert an isolated single character from a string to a char. I'm having trouble getting escaped characters to convert to a single char, as it treats the \\ as a separate character.

String str = "\n"; 
char charVal = str.charAt(0); // Gives charVal as \

Is there a function which interprets the escaped sequence as a single char instead of separate ones?

I'm trying to do this without the Apache commons package.

Thanks!

Answer to updated question: Your results are getting confused somehow. str has exactly one character, so charVal will be that character, the line feed. Check the output, and if it still isn't what you expect, give us an SSCCE demonstrating your problem.

Original answer: temp is not str , and str.charAt(0) would definitely not give \\ as the result. str is a one-character string, so you'd only ever get that one character out, which is a line feed. Likely, you have something further up in your code like:

String temp = "\\n";

In that case, you have a two-character string, where the first is a backslash.

Cant reproduce

    String str = "\n";
    char charVal = str.charAt(0);

    System.out.println(charVal);

gives newline

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM