Boying
Boying

Reputation: 1434

How to convert a char after backslash to the "escape char"

My program is reading text file and converts two adjacent chars (first is backslash and the second is any) to single escape char

char foo(char a, char b){
    ...  // <---how to write this part?
}

expectd: foo('\\','n')->'\n'

I can write the equivalent code in Python3 like this:

tmp = bytearray([ord('\\'), ord(Char)])
Char == tmp.decode('utf-8')  # utf-8 is just python default codec, not related to the question

Upvotes: 1

Views: 175

Answers (1)

chux
chux

Reputation: 153348

Search for a matching acceptable escape character from the list of ", ', ?, \, a, b, t, n, v, f, r

char ab_to_escape(char a, char b) {
  if (a == `\\`) {
    static const char *escapev = "\"\'\?\\abtnvfr";
    static const char *escapec = "\"\'\?\\\a\b\t\n\v\f\r";
    char *p = strchr(escapev, b);
    if (p == NULL || *p == '\0') {
      return b; // TBD this condition, invalid escape character found.
      // Perhaps it begins an octal (0-7) or hexadecimal (x or X) escape sequence?
      // \0 or \x42 etc.
    }
    return escapec[p - escapev];
  }
  return a;// TBD this condition
}

I think OP needs a different function though to handle all escape sequence, many of which are longer than one character after the \\.

int Decode_Escape(char *dest, const char *src) {
  int ch;
  do {
    ch = *src++;
    if (src == '\\') {
      if (simple_escape) Handle_Simple_Escape();            \\ \n \t ...
      else if (octal_escape) Handle_Octal_Escape();         \\ \0 \123
      else if (hex_escape) Handle_Hex_Escape();             \\ \x2 \XAb
      else if (universal_escape) Handle_Universal_Escape(); \\ \uABCD \U12345678
      else { Error(); return 1; }
    } else {
      *dest++ = ch;
    }
  } while (ch);
  return 0;
} 

Upvotes: 2

Related Questions