0

I'm implementing a compiler, and I need to convert from an escape character literal written in source code file to an actual value.

For example I might have a line of source code char = '\\'. I then parse that and get given the string "'\\'", which I need to turn into the actual char '\\'.

char.Parse and char.TryParse both fail when parsing a char in escape sequence form. For example:

char.Parse(@"\\");

Will throw "String must be exactly one character long."

Is there any way to parse everything on this list as a char (ignoring those that are to big to fit in a UTF16 char).

Yair Halberstadt
  • 5,733
  • 28
  • 60
  • How are you getting this "*escape sequence form*" ? who is supplying it, or are you getting confused at what you are seeing in the visual studio editor ? – TheGeneral Nov 16 '19 at 20:13
  • The string shown in the sample is 2 characters long (2 back slashes) - could you please clarify what do you expect to happen? – Alexei Levenkov Nov 16 '19 at 20:13
  • @TheGeneral this is coming in from a parser – Yair Halberstadt Nov 16 '19 at 20:19
  • @AlexeiLevenkov I'm implementing a compiler, and I need to convert from an escape character literal in the form of eg "//" to an actual value. – Yair Halberstadt Nov 16 '19 at 20:21
  • It sounds like https://stackoverflow.com/questions/3298075/can-i-expand-a-string-that-contains-c-sharp-literal-expressions-at-runtime is your actual question... but it is *very* hard to get to from sample in your post... – Alexei Levenkov Nov 16 '19 at 20:23
  • 1
    Sorry @AlexeiLevenkov. I have my head in the context, so it feels very obvious to me, but I can see how it could seem very confusing to someone outside the context. Thanks for the link. – Yair Halberstadt Nov 16 '19 at 20:26

1 Answers1

5

the @ makes it a verbatim string literal. drop that and \ will be treated as the escape char for the next \.

@"\\".Length // 2
"\\".Length // 1
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445