Search code examples
qtpathqt4cross-platform

How to replace '/' with '\\' using QString replace()?


Can anyone help with following? Suppose I have a QString with a filepath stored of a certain file, I want to replace the /(slashes) from it with \\(double backslashes) I tried:

mystring.replace("/","\\");

But it only puts a single \ instead of \\

String before replacement: D:/myfiles/abc.zip

String after replacement: D:\myfiles\abc.zip

Expected string: D:\\myfiles\\abc.zip


Solution

  • You need to use:

    mystring.replace("/","\\\\");
    

    The compiler uses \ as an escape character in strings (for things like \t, \n or \r) so that \\ is actually turned into \. If you need two backslashes, you need to start with four.