programmer
programmer

Reputation: 27

Append "\" character to QString

I have a function that received a string ex. "rn" and I need to append the '\' character to each letter of the string to get "\r\n". In order to append the '\' character, I need to escape it with an additional '\', however that gives me the wrong string.

For example:

QString s = "rn";
QString n = QString("\\%1\\%2").arg(s[0]).arg(s[1]);
qDebug() << n.compare("\r\n");

Outputs 79 instead of 0. I need the first string (s) to be identical to "\r\n" but I'm not sure how I can properly append the '\' character.

Upvotes: 0

Views: 938

Answers (2)

ti7
ti7

Reputation: 18796

You can write "\\" for each '\', typecast int 92 to char, or append '\\' (already a char)

This is necessary because \ is the escape character for strings in C-like and most other languages, and so leads to trouble between how it's displayed and how it's represented

To convince yourself it's the same, you can display / in other ways, such as binary or hex

#include <stdio.h>

int main()
{
  printf("%c\n", '\\');
  printf("%04x\n", '\\');  // display hex
  printf("%04x\n", "\\"[0]);
  printf("%04x\n", 92);
  return 0;
}
% g++ test.py && ./a.out
\
005c
005c
005c

Upvotes: 0

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38508

The way you want does not work, since the escape sequences are interpreted by the compiler, not in runtime.

The quite easy solution is using a function producing required special chars:

char get_special_char(char ch) {
  switch (ch) {
    case 'n':
      return '\n';
    case 'r':
      return '\r';
    default:
     return ch;
  }
}

QString n = QString("%1%2").arg(get_special_char(s[0]))
                           .arg(get_special_char(s[1]));

If there is a lot of chars for conversion to the special symbols, you can use an array char[256] filled with required symbols: a['n'] -> '\n', a['r'] -> '\r'. Be careful with the signed char type.

Upvotes: 1

Related Questions