Search code examples
macosqtreplaceqstring

MAC - QString replace spaces with backslash spaces


Firstly, i have seen this answer.

I'm currently using Qt 5.8 on Mac, and tried below codes:

QString test("/Users/test/Documents/ASCII Tables.pdf");
qDebug() << test.replace(" ", "\\ ");

expected result shoud be like:

"/Users/test/Documents/ASCII\ Tables.pdf"

what i got is two blackslashes are added:

"/Users/test/Documents/ASCII\\ Tables.pdf"

Anyone has suggestion?


Update: (regarding to @docsteer's answer) i intended to use the QString test as part of QProcess:start(), for example:

QProcess process;
process.start("ls " + test);
process.waitForFinished(-1);
qDebug() << process.readAllStandardOutput();
qDebug() << process.readAllStandardError();

and the result is not as expected, as both backslashes are inserted into the command:

""
"ls: /Users/test/Documents/ASCII\\: No such file or directory\nls: Tables.pdf: No such file or directory\n"

Solution

  • What you are seeing there is not the actual content of the string. QDebug escapes the characters as it prints them:

    http://doc.qt.io/qt-5/qdebug.html#operator-lt-lt-16

    Normally, QDebug prints the string inside quotes and transforms non-printable characters to their Unicode values (\u1234).

    To print non-printable characters without transformation, enable the noquote() functionality.

    If you change your code to

    qDebug().noquote() << test.replace(" ", "\\ ");
    

    You will see what you expect - the raw content of the string