Reputation: 254
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!
Upvotes: 2
Views: 2006
Reputation: 128779
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.
Upvotes: 3
Reputation: 33317
Cant reproduce
String str = "\n";
char charVal = str.charAt(0);
System.out.println(charVal);
gives newline
Upvotes: 2