0

Its a simple question, I have a String like this:

String s = "'\n'";  

I want to turn that into a character like this:

char c = '\n';

What can I do?

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
novayhulk14
  • 113
  • 11
  • 1
    Possible duplicate of [How to convert/parse from String to char in java?](https://stackoverflow.com/questions/7853502/how-to-convert-parse-from-string-to-char-in-java) – Bernhard Barker Feb 13 '18 at 15:42
  • Is there always a string with one char ("\n" or "a") in it wrapped by two single quotes? – claudegex Feb 13 '18 at 15:48
  • 1
    If the string is _always_ like that, why not just use `char c = '\n';` instead of picking a single char out of a string? I can't really see any use case for this.. – Jan Gassen Feb 13 '18 at 15:56

1 Answers1

3

There are three characters, first is ', second is \n and third is '. You can get the second one using .charAt(1) since it is zero based indexing:

String s = "'\n'";
char ch = s.charAt(1);
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
  • Or `char ch = (char) (1 << 3 | 1 << 1);`, what's the point? ;) I guess there are even more confusing ways of assigning a newline to a char – Jan Gassen Feb 13 '18 at 16:05